ListBox not returning correct SelectedIndex

G

Guest

I'm going crazy with this. I just added two Listboxes (lbxSource->multiple
selection and lbxDestination -> single selection).
Then:
a) button "Load":
ListItem l0 = new ListItem("01");
lbxDestination.Items.Add(l0); //1st goes to Destination Box
ListItem l1 = new ListItem("02");
lbxSource.Items.Add(l1);
ListItem l2 = new ListItem("03");
lbxSource.Items.Add(l2);
ListItem l3 = new ListItem("04");
lbxSource.Items.Add(l3);
b) button "Insert" (to move an item from Source to Destination):
foreach (ListItem li in lbxSource.Items)
{
if (li.Selected)
{
lbxDestination.Items.Add(li);
lbxDestination.SelectedItem.Value = "01";
li.Selected = false; //otherwise I got a runtime error 'multiple not
allowed in s
}
}
c) a "Show" button that shows the context of the Selected Destination Item:
tbxText.Text = lbxDestination.SelectedItem.Text;

And it's unbelievable, but tbxText.Text always shows "01", no matter what I
selected.
I had this in a real world application and since I couldn't believe it I
wrote a small test-page and it behaves exactly the same.
Is there a workaround to this ? Or am I doing something wrong ?
 
K

Karl Seguin

your step (b) is your problem
First off, chances are you want to create new instance of ListItems instead
of simply copying the reference...so instead of

add(li) do add(new ListItem(li.Text));

secondly, when you do SelectedItem.Value = "01" you are telling it to take
the selected item and putting it's value to 01....since you are copying
references (as above) each new item IS selected (since it was selected in
the previous checkbox) and you are overwriting its value to "01" hence no
matter which you select, they all have the same value...

your insert should look something like:

foreach (ListItem li in lbxSource.Items) {
if (li.Selected) {
lbxDestination.Items.Add(new ListItem(li.Text));
li.Selected = false;
}
}
lbxDestination.SelectedIndex = 0;


karl
 

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,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top