Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1762
  • Last Modified:

How to move items between bound listboxes.

I got 2 listboxes in a window form, one on left and one on right. The
1st listbox have some items while the 2nd listbox is empty. Also there
are 2 buttons between the 2 listboxes which used to move item from/to
the 1st and 2nd listbox

My problem here is that after I bind the data to the 1st listbox (from
a dataTable, using DisplayMember and ValueMember) , and I try to move 1
of the item from this 1st listbox to the 2nd listbox and I want that
the selected item is also removed from the 1st listbox by:

listbox2.Items. Add(listbox1.selecteditem)
listbox1.Items. Remove(listbox1.selecteditem)

But the selected item is not removed from the 1st listbox.

Also on deselect button when i move item from 2nd listbox to 1st
listbox,it displays error message
"Items collection cannot be modified
when the DataSource property is set."

thanks
0
concern_support
Asked:
concern_support
  • 9
  • 6
2 Solutions
 
malikirfan28Commented:
What you can do is,
instead of setting datasource to listbox. You should add items in listbox manually using following code.
foreach (DataRow dr in TableName.Rows)
            {
                listBox1.Items.Add(dr["ColumnName"]);
            }

then your add/remove code will workds.
0
 
malikirfan28Commented:
However if you need to keep Listbox as bounded then you will have to remove items from your bounded datatable and then it will be removed from listbox.

You can remove item from datatable so that it should also removed in listbox as described here.
ArrayList _arrayList = new ArrayList(_listBox1.SelectedIndices);
for(int i = _arrayList.Count; i>0; i--){
      int _target = i-1;
      MyDataTable.Rows.RemoveAt((int)_arrayList[_target]);
}

Open in new window

Thid code snippet will automatically remove the item from listbox.
0
 
concern_supportAuthor Commented:
let me try
0
Get your Disaster Recovery as a Service basics

Disaster Recovery as a Service is one go-to solution that revolutionizes DR planning. Implementing DRaaS could be an efficient process, easily accessible to non-DR experts. Learn about monitoring, testing, executing failovers and failbacks to ensure a "healthy" DR environment.

 
concern_supportAuthor Commented:
Now how to assign value member and display value to the list.
0
 
malikirfan28Commented:
Which way you choosed. Either manually adding of items or Datasource method.
0
 
concern_supportAuthor Commented:
actually i want the list to have a display value and a display member so i can display the value to end user and can use value member behind the scene.
0
 
concern_supportAuthor Commented:
this way
foreach (DataRow dr in TableName.Rows)
            {
                listBox1.Items.Add(dr["ColumnName"]);
            }
0
 
concern_supportAuthor Commented:
i have tried this but not showing value member

For Each dr As DataRow In myListItemsDT.Rows
            lstName.Items.Add(dr("UserName"))
            lstName.ValueMember = dr("ID")
            lstName.DisplayMember = dr("UserName")
Next
0
 
malikirfan28Commented:
Yes when you are adding item manually then DOT NET does not have ability to add DisplayMember and ValueMember. If you need it then you will have to use databound listboxes.

Here is the code snippet to bound your two list boxes at FORM_LOAD or whenever you want to bound these.

DataTable mySourceTable = GetDataFromDB();
            DataTable mySelectedTable = mySourceTable.Clone();

            listBox1.DataSource = mySourceTable;
            listBox1.DisplayMember = "Name";
            listBox1.ValueMember = "ID";

            listBox2.DataSource = mySourceTable;
            listBox2.DisplayMember = "Name";
            listBox2.ValueMember = "ID";

Open in new window


and when you want to move item then you can do it as
DataRow dr = (DataRow)listBox1.SelectedItem;
            mySelectedTable.Rows.Add(dr.ItemArray);

            mySourceTable.Rows.Remove(dr);

Open in new window

0
 
concern_supportAuthor Commented:
now the following code gives this error.

unable to cast object of type system.data.datarowview to type system.data.datarow

please write in vb.net code
Dim dr As DataRow = lstUsers.SelectedItem
            Dim mySelectedTable As New DataTable
            'mySelectedTable.Rows.Add(dr.ItemArray);
            mySelectedTable.Rows.Add(dr.ItemArray)


            myListItemsDT.Rows.Remove(dr)

Open in new window

0
 
concern_supportAuthor Commented:
And two things other that i am concern about.
1. How if i want to remove more then one item at once?
2. Will it delete data from database table?
0
 
malikirfan28Commented:
Here is the code which will also remove more than one selected items from one list and move it to other list.

if (listBox1.SelectedItems == null)
                MessageBox.Show("Select items to move.");
           ArrayList selectedObjects = new ArrayList(listBox1.SelectedIndices);

           for (int i = 0; i < selectedObjects.Count; i++)
            {
                DataRowView dr = (DataRowView)listBox1.Items[((int)selectedObjects[i])];
                mySelectedTable.Rows.Add(dr.Row.ItemArray);
               // mySourceTable.Rows.Remove(dr.Row);
           }

           for (int i = selectedObjects.Count; i > 0; i-- )
           {
               mySourceTable.Rows.RemoveAt(((int)selectedObjects[i - 1]));
           }

Open in new window


as for as your point 2 is concerned, yes it is removing data from in-memory datatable (not from database). However later if you again need the complete datatable as you got from database then you can simply merge the two datatables which we created for two list boxes.
0
 
malikirfan28Commented:
Here is the same above code in VB.Net

 If ListBox1.SelectedItems Is Nothing Then
            MessageBox.Show("Select items to move.")
        End If
        Dim selectedObjects As New ArrayList(ListBox1.SelectedIndices)

        For i As Integer = 0 To selectedObjects.Count - 1
            Dim dr As DataRowView = DirectCast(ListBox1.Items(CInt(selectedObjects(i))), DataRowView)
            mySelectedTable.Rows.Add(dr.Row.ItemArray)
        Next

        For i As Integer = selectedObjects.Count To 1 Step -1
            mySourceTable.Rows.RemoveAt(CInt(selectedObjects(i - 1)))
        Next

Open in new window


Kindly let me know if it solves your problem.
0
 
CodeCruiserCommented:
Keep using the DataTable as the datasource and instead of modifying the listbox to add/remove items, add/remove items from the datatable

dTable.Select("columnname=" & listbox1.SelectedValue)(0).Delete

Dim drow as DataRow = dTable.NewRow()
drow(0)=somevalue
drow(1)=someothervalue
dTable.Rows.Add(drow)
0
 
concern_supportAuthor Commented:
Hi CodeCruiser

You are right, but can you tell me how to handle multiple selected items in a list.

I mean my listbox property is set to multiExtend if a user select multi rows so then how to move all selected rows at once to listbox 2.
0
 
concern_supportAuthor Commented:
i did as followed, but it is moving all item at once.
Do While lstUsers.SelectedItems.Count > 0
            ' If lstUsers.Items.Count > 0 Then
            Dim drow As DataRow = mySelectedItemsDT.NewRow()
            drow("ID") = lstUsers.SelectedValue
            drow("UserName") = lstUsers.SelectedItem("UserName")
            mySelectedItemsDT.Rows.Add(drow)
            myListItemsDT.Select("ID=" & lstUsers.SelectedValue)(0).Delete()
            ' End If
        Loop

Open in new window

0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 9
  • 6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now