我几天前开始编程,但我一直在试图找出为什么我的代码不起作用。非常感谢任何帮助!
这是我的代码:
...
public partial class Form1 : Form
{
List<String> names = new List<String>();
BindingSource namesBindingSource = new BindingSource();
public Form1()
{
InitializeComponent();
namesBindingSource.DataSource = names;
listBox1.DataSource = namesBindingSource;
}
private void button1_Click(object sender, EventArgs e) {
if (CmdClockInOut.Text == "XYZ")
{
names.Add("123");
}
}
private void Form1_Load(object sender, EventArgs e)
{
namesBindingSource.DataSource = names;
listBox1.DataSource = namesBindingSource;
}
}
只有在公共Form1()中输入
names.Add("123");
时,数据才会显示在列表框中:
public Form1()
{
InitializeComponent();
namesBindingSource.DataSource = names;
listBox1.DataSource = namesBindingSource;
names.Add("123");
}
我认为LarsTech的答案是正确的。 只是为了确定,当你说:
只有当names.Add("123");时数据才会显示在列表框中。已进入公众视野
您的代码是:
public partial class Form1 : Form
{
List<String> names = new List<String>();
BindingSource namesBindingSource = new BindingSource();
public Form1()
{
InitializeComponent();
namesBindingSource.DataSource = names;
listBox1.DataSource = namesBindingSource;
names.Add("123");
}
private void Form1_Load(object sender, EventArgs e)
{
namesBindingSource.DataSource = names;
listBox1.DataSource = namesBindingSource;
}
}
如果是的话。 我认为您在负载中重新分配列表这一事实给您留下了存在绑定的印象
你可以尝试这样的事情:
public partial class Form1 : Form
{
private BindingList<String> names;
private BindingSource namesBindingSource;
public Form1()
{
namesBindingSource = new BindingSource();
names = new BindingList<String>();
namesBindingSource.DataSource = names;
listBox1.DataSource = namesBindingSource;
}
private void button1_Click(object sender, EventArgs e)
{
if (CmdClockInOut.Text == "XYZ")
{
names.Add("123");
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}