transfer items from one listbox to another - c#

so far i have accomplished transfer a single select item from one lb1 to lb2 and vice versa. Now the problem is transfering the whole list of data from lb1 to lb2 and vice versa. if anyone could help please.
using for loop will be much better.
i am using the following code:
private void add_Click(object sender, EventArgs e)
{
if (lb1.SelectedItem != null)
{
lb2.Items.Add(lb1.SelectedItem);
lb1.Items.Remove(lb1.SelectedItem);
}
else
{
MessageBox.Show("No item selected");
}
}
private void remove_Click(object sender, EventArgs e)
{
if (lb2.SelectedItem != null)
{
lb1.Items.Add(lb2.SelectedItem);
lb2.Items.Remove(lb2.SelectedItem);
}
else
{
MessageBox.Show("No item selected");
}
}
private void addall_Click(object sender, EventArgs e) //problem is here. adding all the items from lb1 to lb2
{
for (int i = 0; i < lb1.SelectedItems.Count; i++)
{
lB2.Items.Add(lb1.SelectedItems[i].ToString());
}
}
private void removeall_Click(object sender, EventArgs e) //problem is here. adding all the items from lb2 to lb1
{
}

Because you want to transfer all of the items from one list box to another not only the selected items you must loop for every item in the list box and not only the selected items.
So change your usage of ListBox.SelectedItems to ListBox.Items and your code should work as expected assuming you remember to remove the items as well.
for (int i = 0; i < lb1.Items.Count; i++)
{
lB2.Items.Add(lb1.Items[i].ToString());
}
lb1.Items.Clear();

You could do something like this:
private void addall_Click(object sender, EventArgs e)
{
foreach (var item in lb1.Items)
{
lB2.Items.Add(item);
}
}
This would loop through your list and add them all. You would do the reverse for lb2->lb1.

Simply iterate over all Items of the list and add each element to the next list. At the end simply remove all Items.
foreach (var item in listBox1.Items)
{
listBox2.Items.Add(item);
}
listBox1.Items.Clear();

Related

How to replace previous item of listbox with next item using backgroundworker c#?

I am adding items to the listbox using backgroundworker. It is showing all the items present in the list one by one after some interval of time. I want to show only current item in the list and not all the items.
This is what I have tried.
private void backgroundWorker3_DoWork(object sender, DoWorkEventArgs e)
{
List<string> result = new List<string>();
var found = obj.getFiles();//List<strings>
if (found.Count != 0)
{
for (int i = 0; i < found.Count; i++)
{
int progress = (int)(((float)(i + 1) / found.Count) * 100);
if (found[i].Contains("SFTP"))
{
result.Add(found[i]);
(sender as BackgroundWorker).ReportProgress(progress, found[i]);
}
System.Threading.Thread.Sleep(500);
}
e.Result = result;
}
}
private void backgroundWorker3_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState != null)
listBox3.Items.Add(e.UserState);
}
I want to show only current item in the list and not all the items.
Although this is a bit of a hack, I think it should work for what you describe:
// just call clear first
listBox3.Items.Clear();
listBox3.Items.Add(e.UserState);
Truth be told, are you sure you want a ListBox in this circumstance? After all, it's not really a list, it's only an item.

Selecting Multiple Items From ListBox causes Collection was modified; enumeration operation may not execute

This is a simple code in which i am Transferring Items of one listBox to one Another on btnAdd_Click Event and btnRemove_Click Event resp.
This was working Fine when The selectionMode="Single" and at that point of time i had no need to use foreach inbtn_Add_Click. But Now i've changed selectionMode="Multiple" and used foreach in btnAdd_Click and when i am selecting multiple items from ListBox it is creating the following Error:-
Collection was modified; enumeration operation may not execute
class Movies
{
private Int32 _Id;
private string _movieName;
public Int32 Id
{
get { return _Id; }
set { _Id = value; }
}
public string movieName
{
get { return _movieName; }
set { _movieName = value; }
}
public Movies(Int32 ID, string MovieName)
{
Id = ID;
movieName = MovieName;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Movies> list = new List<Movies>();
list.Add(new Movies(1, "Movie1"));
list.Add(new Movies(2, "Movie2"));
list.Add(new Movies(3, "Movie3"));
list.Add(new Movies(4, "Movie4"));
list.Add(new Movies(5, "Movie5"));
list.Add(new Movies(6, "Movie6"));
list.Add(new Movies(7, "Movie7"));
lstMain.DataSource = list;
lstMain.DataBind();
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
foreach (ListItem list in lstMain.Items)// Here the error comes
{
if(list.Selected)
{
lstFAvourite.ClearSelection();
lstFAvourite.Items.Add(list);
lstMain.Items.Remove(list);
}
}
}
protected void btnRemove_Click(object sender, EventArgs e)
{
ListItem list = lstFAvourite.SelectedItem;
lstMain.ClearSelection();
lstMain.Items.Add(list);
lstFAvourite.Items.Remove(list);
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (ListItem item in lstFAvourite.Items)
{
lbl1.Text += "<li>" + item.Text;
}
}
Please tell me what is going wrong with the foreach loop in btnAdd_Click Event....
Thanks..
You can't remove items from an enumeration while you are looping through it using a foreach, which is what the error message is trying to tell you.
Switching to a straight for loop will get your code to execute:
protected void btnAdd_Click(object sender, EventArgs e)
{
for(var i=0; i<lstMain.Items.Count; i++)
{
var list = lstMain.Items[i];
lstFAvourite.ClearSelection();
lstFAvourite.Items.Add(list);
lstMain.Items.Remove(list);
i--;
}
}
However, I believe this code will add all items from lstMain to lstFAvourite. I think perhaps that we should be looking at the Selected property of the ListItem as well in the for loop. For example:
protected void btnAdd_Click(object sender, EventArgs e)
{
for (var i = 0; i < lstMain.Items.Count; i++)
{
var list = lstMain.Items[i];
if(!list.Selected) continue;
lstFAvourite.ClearSelection();
lstFAvourite.Items.Add(list);
lstMain.Items.Remove(list);
//Decrement counter since we just removed an item
i--;
}
}
Another method.
lstMain.Items
.Cast<ListItem>()
.ToList()
.ForEach( item =>
{
if(item.Selected)
{
lstFAvourite.Items.Add(item);
lstMain.Items.Remove(item);
}
}
);
lstFAvourite.ClearSelection();
N.B: much slower than the for loop method.
If you try to remove list box items using a for loop using an increment (++) statement, eventually that loop will throw out of bounds error failing to finish removing all the items you want. Use decrement (--) instead.
The error Collection was modified; enumeration operation may not execute is because, while you are deleting the items from the list its affecting the sequence. You need to iterate the items in reverse order for this.
for (int i = lstMain.Items.Count; i > 0; i--)
{
ListItem list = lstMain.Items[i];
lstFAvourite.ClearSelection();
lstFAvourite.Items.Add(list);
lstMain.Items.Remove(list);
}

What control should I use for multiple selection of item in winforms C#?

I am really confused on thinking which control to use for my purpose.
I am having list of items say item1 to item10. User can select 4 or 5 items in any order.
Now user selected items has to be separated in same order.
For example, if the user selected the items in following order, item4, item8, item3 and item2.
I want it in the same order. item4,item8,item3,item2.
How do I achieve this in winforms control?
It is not a very nice solution but I wrote it as you asked.
Set the SelectionMode of your ListBox to MultiExtended or MultiSimple as you need.
Then write this code in SelectedIndexChanged event of your ListBox:
List<string> orderedSelection = new List<string>();
bool flag = true;
private void listBox3_SelectedIndexChanged(object sender, EventArgs e)
{
if (flag)
{
flag = false;
var list1 = listBox3.SelectedItems.Cast<string>().ToList();
if (listBox3.SelectedItems.Count > orderedSelection.Count)
{
orderedSelection.Add(list1.Except(orderedSelection).First());
}
else if (listBox3.SelectedItems.Count < orderedSelection.Count)
{
orderedSelection.Remove(orderedSelection.Except(list1).First());
}
var list2 = listBox3.Items.Cast<string>().Except(list1).ToList();
listBox3.Items.Clear();
for (int i = 0; i < list1.Count; i++)
{
listBox3.Items.Add(list1[i]);
listBox3.SelectedIndex = i;
}
foreach (string s in list2)
{
listBox3.Items.Add(s);
}
flag = true;
}
}
When user selects an item, It comes to first of the list and the rest of the items comes next.
Also, there is an alternative way. You can use a CheckedListBox with two extra button for moving selected items up and down. So user can change the order of selected items.
This solution uses CheckListBox's ItemCheck event along with a private List to keep track of the click items order.
protected List<string> clickOrderList = new List<string>();
private void Form1_Load(object sender, EventArgs e)
{
// Populate the checked ListBox
this.checkedListBox1.Items.Add("Row1");
this.checkedListBox1.Items.Add("Row2");
this.checkedListBox1.Items.Add("Row3");
this.checkedListBox1.Items.Add("Row4");
}
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (sender != null && e != null)
{
// Get the checkListBox selected time and it's CheckState
CheckedListBox checkListBox = (CheckedListBox)sender;
string selectedItem = checkListBox.SelectedItem.ToString();
// If curent value was checked, then remove from list
if (e.CurrentValue == CheckState.Checked &&
clickOrderList.Contains(selectedItem))
{
clickOrderList.Remove(selectedItem);
}
// else if new value is checked, then add to list
else if (e.NewValue == CheckState.Checked &&
!clickOrderList.Contains(selectedItem))
{
clickOrderList.Insert(0, selectedItem);
}
}
}
private void ShowClickOrderButton_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach (string s in clickOrderList)
{
sb.AppendLine(s);
}
MessageBox.Show(sb.ToString());
}

Error: foreach statement cannot operate on variables of type 'System.Web.UI.WebControls.ListItem'

I am trying to move multiple selected item from one ListBox to another ListBox using this code
protected void imgbtnMoveRightListBox_Click(object sender, ImageClickEventArgs e)
{
foreach (var item in lstboxSkill.SelectedItem)
{
lstBBoxSkill2.Items.Add(item);
}
}
but it shows an error
foreach statement cannot operate on variables of type
'System.Web.UI.WebControls.ListItem' because
'System.Web.UI.WebControls.ListItem' does not contain a public
definition for 'GetEnumerator'
I don't know why this error occured.
Please help me to fix it
Check this code.
protected void imgbtnMoveRightListBox_Click(object senderImageClickEventArge)
{
foreach (ListItem item in lstboxSkill.Items)
{
lstBBoxSkill2.Items.Add(item);
}
}
Please check this snap shot I have created and its working fine.
and the code behind code is given below:
protected void Page_Load(object sender, EventArgs e)
{
lstboxSkill.Items.Add("ASP.Net");
lstboxSkill.Items.Add("C#");
lstboxSkill.Items.Add("AJAX");
lstboxSkill.Items.Add("JavaScript");
lstboxSkill.Items.Add("HTML");
lstboxSkill.Items.Add("HTML5");
lstboxSkill.Items.Add("JQuery");
}
protected void imgbtnMoveRightListBox_Click(object sender, EventArgs e)
{
foreach (ListItem Item in lstboxSkill.Items)
{
if (Item.Selected == true)
{
lstBBoxSkill2.Items.Add(Item);
}
}
}
This is because the SelectedItem property returns only the item with the lowest index out of the list of items selected. You should change your code as
protected void imgbtnMoveRightListBox_Click(object sender, EventArgs e)
{
foreach (ListItem Item in lstboxSkill.Items)
{
if (Item.Selected == true)
{
lstBBoxSkill2.Items.Add(Item);
}
}
}
And set both listbox SelectionMode="Multiple".
Hope this will help you. Don't forget marked as answer
Thanks
Solomon S.
lstboxSkill.SelectedItem is a ListItem, which is neither an array nor an object collection that implements the System.Collections.IEnumerable<T> or System.Collections.Generic.IEnumerable<T> interface, so it's not possible to do foreach against it.
I think this is what you're looking for:
foreach (var item in lstboxSkill.Items)
{
if (item.Selected)
{
lstBBoxSkill2.Items.Add(item);
}
}
protected void imgbtnMoveRightListBox_Click(object sender, EventArgs e)
{
lbltxt.Visible = false;
if (ListBox1.SelectedIndex >= 0) // in this we are checking whether a single item is clicked.
{
for (int i = 0; i < ListBox1.Items.Count; i++) // we are looping through the list box items
{
if (ListBox1.Items[i].Selected) // finding the selected items
{
if (!arraylist1.Contains(ListBox1.Items[i]))
{
arraylist1.Add(ListBox1.Items[i]); //if found then adding those items to the array list
}
}
}
for (int i = 0; i < arraylist1.Count; i++)
{
if (!ListBox2.Items.Contains(((ListItem)arraylist1[i])))
{
ListBox2.Items.Add(((ListItem)arraylist1[i])); // we are adding the array elements to the second list box
}
ListBox1.Items.Remove(((ListItem)arraylist1[i]));
}
ListBox2.SelectedIndex = -1;
}
else
{
lbltxt.Visible = true;
lbltxt.Text = "Please select atleast one in Listbox1 to move";
}
}
Source

How to move multiple selected item from one listbox to another listbox?

I have two listboxes named listBox1 and listBox2 with 4 items (strings) in both listboxes. I can select multiple items from both listboxes. I have also two buttons.
On clicking button1, I have to move multiple selected items from listBox1 to listBox2. Similarly, on clicking button2, I have to move multiple selected items from listBox2 to listBox1.
How can it be done?
private void MoveListBoxItems(ListBox source, ListBox destination)
{
ListBox.SelectedObjectCollection sourceItems = source.SelectedItems;
foreach (var item in sourceItems)
{
destination.Items.Add(item);
}
while (source.SelectedItems.Count > 0)
{
source.Items.Remove(source.SelectedItems[0]);
}
}
Use:
On the click event of your move from 1 to 2 button:
MoveListBoxItems(listBox1, listBox2);
To move them back:
MoveListBoxItems(listBox2, listBox1);
A ListBox has a SelectedItems property you can use to copy the items in the click event handler of the button. Like this:
foreach(var item in listBox1.SelectedItems)
{
listBox2.Items.Add(item);
}
private void Move(ListControl source, ListControl destination)
{
List<ListItem> remove = new List<ListItem>();
foreach(var item in source.Items)
{
if(item.Selected == false) continue;
destination.Items.Add(item);
remove.Add(item);
}
foreach(var item in remove)
{
source.Items.Remove(item);
}
}
then you can call it like this
Move(listbox1, listbox2);
//or
Move(listbox2, listbox1);
According to this question How to remove multiple selected items in ListBox?
private void button1_Click(object sender, EventArgs e)
{
for(int x = listBox1.SelectedIndices.Count - 1; x>= 0; x--)
{
int idx = listBox1.SelectedIndices[x];
listBox2.Items.Add(listBox1.Items[idx]);
listBox1.Items.RemoveAt(idx);
}
}
You can do like this.
private void button1_Click(object sender, EventArgs e)
{
foreach (var item in listBox1.SelectedItems)
{
listBox2.Items.Add(item);
}
for (int s = 0; s < listBox1.Items.Count; s++)
{
for (int t = 0; t < listBox2.Items.Count; t++)
{
if (listBox1.Items[s].ToString().Equals(listBox2.Items[t].ToString()))
{
listBox1.Items.RemoveAt(s);
}
}
}
}
private void move(ListBox source, ListBox destination) {
for (int i = 0; i <= source.Items.Count-1; i++)
{
destination.Items.Add(source.Items[i]);
}
source.Items.Clear();
}
private void Btn_Right_Click(object sender, EventArgs e)
{
while(ListBox_Left.SelectedItems.Count!=0)
{
ListBox_Right.Items.Add(ListBox_Left.SelectedItem);
ListBox_Left.Items.Remove(ListBox_Left.SelectedItem);
}
}
private void Btn_Left_Click(object sender, EventArgs e)
{
while (ListBox_Right.SelectedItems.Count != 0)
{
ListBox_Left.Items.Add(ListBox_Right.SelectedItem);
ListBox_Right.Items.Remove(ListBox_Right.SelectedItem);
}
}

Categories

Resources