Hi, I hope you can help.

I'm creating a simple C# (VS2010) form which starts with one list box lBModel and upon selection dynamically creates another lBFirmware which is populated with items and then added to a panel.

When this is selected I need to use the SelectedItem value to determine a further state but from within my function I can't access the value.

If I examine sender I can see the selected value but I'm not sure how (or even if it is possible) to obtain this value.

private void lBModel_SelectedIndexChanged(object sender, EventArgs e)

            //create new listbox
            ListBox lBFirmware = new ListBox();
            lBFirmware.Location = new System.Drawing.Point(33, 2);
            lBFirmware.Name = "Firmware";
            lBFirmware.Size = new System.Drawing.Size(120, 17);
            lBFirmware.TabIndex = 1;
            //add a single item to check
            lBoxTest1.Items.AddRange(new object[] {"Test Value"});
            //create event for selection
            lBFirmware.SelectedIndexChanged += new System.EventHandler(lBFirmware_SelectedIndexChanged);
            //add new listbox to panel pMainFields

        private void lBFirmware_SelectedIndexChanged(object sender, EventArgs e)

        //do something with the value here... but SelectedItem doesn't exist :-(


Hello, wcroome.
I've created a Test Application, and when I add Items to lBFirmware , rather than lBoxTest1 , I'm able to obtain the selected Index in the specified handler:

private void lBFirmware_SelectedIndexChanged(object sender, EventArgs e) {
     ListBox lb = sender as ListBox;
     int selectedIndex = lb.SelectedIndex; //all ok here ;)

Ah, so my missing link was to assign the sender to a local ListBox before accessing the properties. Thanks

This question has already been answered. Start a new discussion instead.