Duplicate entries in ListBox?

R

rcarboni

When duplicate entries are made to a
System.Web.UI.WebControls.ListBox, the SelectedIndex
returned always refers to the first occurance.

For example:

System.Web.UI.WebControls.ListBox ListBox1;

ListBox1.Items.Add(new ListItem("Item 1"));
ListBox1.Items.Add(new ListItem("Item 2"));
ListBox1.Items.Add(new ListItem("Item 3"));
ListBox1.Items.Add(new ListItem("Item 4"));
ListBox1.Items.Add(new ListItem("Item 2"));
ListBox1.Items.Add(new ListItem("Item 1"));

If you highlight the second occurance of "Item 2",
ListBox1.SelectedIndex is set to the first occurance
of "Item 2" with a value of 1.

Does this mean that you cannot have duplicate entries in a
ListBox? I could not find any info about this in the help.
 
A

Alvin Bruney

I've seen this before first hand. I think it is a bug since the value
property can be different meaning that the listitem IS not identical. I
didn't submit it as a bug to MS. Would u?
 
F

Felix Chan

You may try checking the 'Selected' property of all the
ListItem in your ListBox by using a "foreach loop" and see
if it give you a "true" in the second "Item 2".

Change the "log.Debug" to what you want to display the
debug message.....

foreach (ListItem li in ListBox1.Items)
{
if (li == null)
{
log.Debug("ListItem --- null.");
}
else
{
log.Debug("ListItem --- text:'" + li.Text
+ "', value:'" + li.Value + "', selected:'" + li.Selected
+ "'");
}
}
 
F

Felix Chan

Another idea... You may add a sequence number to all the
ListItem. The reason is that you have no Value in the
ListItem and .NET can only check the Text property to see
which item user selected. When it come to the first "Item
2", it return 1 to you.

Try this:

System.Web.UI.WebControls.ListBox ListBox1;

ListBox1.Items.Add(new ListItem("Item 1", "0"));
ListBox1.Items.Add(new ListItem("Item 2", "1"));
ListBox1.Items.Add(new ListItem("Item 3", "2"));
ListBox1.Items.Add(new ListItem("Item 4", "3"));
ListBox1.Items.Add(new ListItem("Item 2", "4"));
ListBox1.Items.Add(new ListItem("Item 1", "5"));

When postback, the SelectedIndex should be correct.

Regards,
Felix
 
R

rcarboni

Yes, this will work, but then we have to always make sure
that the text and value are unique? This still does not
seem to work correctly.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top