ListBox Problem

J

Jack Lewis

Dear All.

I have a Web Form which has 2 ListBoxes and an Add Button. I have 4 items in
my First List Box. What I want to do is shift the selected Items from first
List Box to 2nd List Box.The selection mode of both of my ListBoxes is
"Multiple". I am able to add the selected Items from the 1st List Box to 2nd
List Box. But The problem is that when I have added the selected items from
1st List Box to 2nd List Box. the added Items still seem to appear in the 1st
List Box. This doesn't happen when the Selection Mode of my ListBox is
"Single". I want the selected Items to be deleted once the they have been
copied into 2nd List Box.
Below is my Code:


private void Page_Load(object sender, System.EventArgs e)
{ // Put user code to initialize the page here

if(!IsPostBack)

{

ListBox1.Items.Add("UK");
ListBox1.Items.Add("USA"); ListBox1.Items.Add("Ireland");
ListBox1.Items.Add("Wales");
}

}

private void btnAdd_Click(object sender, System.EventArgs e)
{
if (ListBox1.SelectedItem != null)
{
foreach(ListItem i in ListBox1.Items)
{
if(i.Selected==true)
{
strSelection = i.Text;

if (ListBox2.Items.FindByText(strSelection)== null )
{
ListBox2.Items.Add(strSelection);
ListBox2.SelectedIndex =0;

}

//*** Here is the Code where I am removing the Items from ListBox1**//


for(int counter = 0; counter<=ListBox1.Items.Count-1; counter++)
{
if (ListBox1.Items[counter].Selected == true)
{
ListBox1.Items.RemoveAt(counter);
}
}

I don't know whats wrong with the above code.But it doesn't seem to remove
the selected items from the 1st List Box properly. I mean it does remove
Items frm the 1st list Box. But not the all which I have selected.

Any help would be greatly appreciated.

cheers,
Jack
 
M

Microsoft

Change your for loop to count down instead of up:
for (int counter = ListBox1.Items.Count-1; counter >= 0; counter--)
 

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,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top