Is ListBox2.DataSource = SqlDataSource2 ???
I can only assume this since I don't see any code in there where you assign ListBox2.Items.
I am assuming SqlDataSource2 will only retrieve one item at a time, yes?
Well, basically your code is rebinding ListBox2 to whatever currently is in SqlDataSource2, and you are doing it every single time the code loop around.
Try to see it in your mind, say you have item 1, 3 and 5 checked in your gridview (let's just pretend the key is also 1, 3, and 5).
The first time the code enter the loop
you retrieve some key pair value using SqlDataSource2 where the key
value is 1 and you bind it to ListBox2 (this is basically clearing all
the current item in ListBox2 and reload the data in SqlDataSource2 into
its item collection).
Now the code loop around,
you retrieve some other key pair value using SqlDataSource2 where the key
value is 3 and you bind it to ListBox2 (again, this is basically clearing all
the current item in ListBox2 and reload the data in SqlDataSource2 into
its item collection).
Can you see the problem?
What you want to do is probably can be done without automatically binding ListBox2 and just do it manually.
Before you enter the loop, manually clear ListBox2.Items (ListBox2.Items.Clear())
While you are in the loop, do whatever you need to do to get the key value pair based on the current selected / checked item key
and assign it to ListBox2.Items (ListBox2.Items.Add(new ListItem(valueToBeDisplayed, keyForTheDisplayedValue)
Jimmy Chandra
Blogging at
Incoherent RamblingMark this post as Answer if you think it helped you solve the problem.