简体   繁体   中英

ListBox1_SelectedIndexChanged not firing

I'm trying to make a windows forms app for the first time. I have two list boxes. The first one is being populated from a .txt-file when starting the program:

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM