• Notice regarding image hosts and attachments. See here.

ASP.NET ListBox problem

Associate
Joined
24 Jul 2003
Posts
1,420
Location
West Mids
Wondering anyone here can shed some light on this problem I'm having. I'm populating a listbox with items from a database - all have different text, but some have same values.

When the OnSelectedIndexChanged event fires, it registers the wrong item in the list as having been selected; if I select item 3 in the list, it thinks item 1 has been selected. I've never had this problem before and I'm either missing something silly or it's something I just didn't understand.

Code:
....
//populating the listbox
DataTable dt = MethodThatGetsDataFromDB();

foreach(DataRow rows in dt.rows)
{
[INDENT]listBox1.Items.Add(new ListItem(rows["col1"].ToString(), rows["col2"].ToString());[/INDENT]
}
....

Anyone have any ideas why it's insisting on selecting the wrong index? :(
 
Aye they do - having done some googling, do the controls have to have unique values?

*Edit* Answered my own question it seems - yes they do have to have unique values. I changed the values of the data in the DB to have unique values and the problem has gone away *sigh* at least I know why now - just need to find an alternative solution now.
 
Last edited:
Just added a counter in the foreach loop and append ";" + counter.ToString() at the end of the value, so it comes out as unique. All it does then is substring the value up till last index of ;

This isn't a production system so doesn't need anything fancy :)
 
Back
Top Bottom