I am trying to move items from one list box to another if they are multiple but I am able to move only few, means less than the count. I am not able to implement via for each and for loop as well.
if (AdvLst.SelectedIndex > -1)
{
for (int i = 0; i <= AdvLst.Items.Count - 1; i++)
{
if (AdvLst.Items[i].Selected)
{
string _value = AdvLst.SelectedItem.Value;
string _text = AdvLst.SelectedItem.Text;
ListItem item = new ListItem();
item.Text = _text;
item.Value = _value;
SelectedMortLst.Items.Add(AdvLst.Items[i]);
AdvLst.Items.Remove(AdvLst.Items[i]);
}
}
}
and via foreach loop:
foreach (ListItem li in AdvLst.Items)
{
if (li.Selected == true)
{
SelectedMortLst.Items.Add(AdvLst.SelectedItem);
AdvLst.Items.Remove(AdvLst.SelectedItem);
}
}
Solution 1
Solution 2 (almost the same)
Solution 3, for loop code corrected
cause if you remove an item in the for loop, the count of the collection changes, and the item which is at
i+1place when you remove item has now indexi. Withi--, your for loop is adapted to that change