[英]ListBox1_SelectedIndexChanged not firing
I'm trying to make a windows forms app for the first time.我第一次尝试制作 Windows 窗体应用程序。 I have two list boxes.我有两个列表框。 The first one is being populated from a .txt-file when starting the program:第一个是在启动程序时从 .txt 文件填充的:
public Form1()
{
InitializeComponent();
string[] lines = File.ReadAllLines("C:\\Users\\Mitarbeiter.txt");
ListBox listBoxMitarbeiter = new ListBox();
listBoxMitarbeiter.Size = new System.Drawing.Size(200, 350);
listBoxMitarbeiter.Location = new System.Drawing.Point(30, 100);
this.Controls.Add(listBoxMitarbeiter);
listBoxMitarbeiter.SelectionMode = SelectionMode.MultiExtended;
listBoxMitarbeiter.BeginUpdate();
int c = 0;
foreach (string line in lines)
{
listBoxMitarbeiter.Items.Insert(c, line);
c++;
}
listBoxMitarbeiter.EndUpdate();
}
Now I want the second list box to be created and populated when a item/index is selected in the first one:现在我希望在第一个列表框中选择项目/索引时创建并填充第二个列表框:
private void listBoxMitarbeiter_SelectedIndexChanged(object sender, System.EventArgs e)
{
ListBox listBox2 = new ListBox();
listBox2.Size = new System.Drawing.Size(200, 350);
listBox2.Location = new System.Drawing.Point(200, 100);
this.Controls.Add(listBox2);
listBox2.SelectionMode = SelectionMode.MultiExtended;
listBox2.BeginUpdate();
listBox2.Items.Insert(2,"it works");
listBox2.EndUpdate();
}
I've read that you are supposed to somehow link the event with the listbox.我读过您应该以某种方式将事件与列表框联系起来。 How?如何? Or is it something else entirely.或者它是完全不同的东西。 Please help.请帮忙。
You need to add an event handler to the listbox:您需要向列表框添加一个事件处理程序:
listBoxMitarbeiter.SelectedIndexChanged +=
new EventHandler(listBoxMitarbeiter_SelectedIndexChanged);
This way, the listBoxMitarbeiter_SelectedIndexChanged()
method will be called on each SelectedIndexChanged
event.这样,将在每个SelectedIndexChanged
事件上调用listBoxMitarbeiter_SelectedIndexChanged()
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.