I've got a listbox in C# that's dynamically filled. I've got a problem with the selectedindex_changed of the listbox. Everytime it gives the value of the last item in the listbox and not the one I selected. I've got that same problem with a combobox on another page.
I don't know why this happens this way. Does anyone knows what I'm doing wrong?
First I make a new object Item to put text with the ID as the value in the listbox.
public class Item
{
public string Text { get; set; }
public int Value { get; set; }
public override string ToString()
{
return Text;
}
}
Here I fill the listbox with the text and the ID as its value. This works fine, the listbox gets filled as it should be.
private void FormDeelnemers_Load(object sender, EventArgs e)
{
BLPersoon blPersoon = new BLPersoon();
DBOpdracht.PersoonDataTable personen = blPersoon.GetAllPersonen();
//Item item = new Item(); -> edit: delete this
foreach (DBOpdracht.PersoonRow persoon in personen)
{
Item item = new Item(); -> edit: add this here
item.Text = persoon.naam;
item.Value = persoon.ID;
listBoxPersonen.Items.Add(item);
}
}
Here is the problem. It gives the value of the last item in the listbox and not the one I've selected. How do I get the selected one?
private void listBoxPersonen_SelectedIndexChanged(object sender, EventArgs e)
{
int nummer = (listBoxPersonen.SelectedItem as Item).Value;
MessageBox.Show(nummer.ToString());
//MessageBox.Show(listBoxPersonen.SelectedItem.ToString()); -> same problem
}