The winfrom ListBox data source binding list interface is not updated. The problem is that the bound data source cannot be crud.
Scenario: Obtain the selected items of a ListBox and add them to another ListBox solution-1: do not directly bind datasource first bind ListBox to bindingsource BS and bind BS to code case: 1-1: updatable add all
private void btnAdd_Click(object sender, EventArgs e) { ListBox.SelectedObjectCollection selectObj = this.listLeft.SelectedItems;foreach (DataRowView item in selectObj){Sta sta = new Sta();sta.STCD = int.Parse(item.Row.ItemArray[0].ToString());sta.Name = item.Row.ItemArray[1].ToString();list.Add(sta);}BindingSource bs = new BindingSource();bs.DataSource = list;this.listRight.DataSource = bs;this.listRight.DisplayMember = "NAME";this.listRight.ValueMember = "STCD"; }
1-2: Remove duplicate items after modification
Private void btnadd_click (Object sender, eventargs e) {ListBox. selectedobjectcollection selectobj = This. listleft. selecteditems; foreach (datarowview item in selectobj) {bool B = true; // to check whether the listright item already exists, do not add foreach (model. sta rightitem in this. listright. items) {If (rightitem. name = item. row. itemarray [1]. tostring () {B = false ;}} if (B) {sta = new sta (); Sta. stcd = int. parse (item. row. itemarray [0]. tostring (); Sta. name = item. row. itemarray [1]. tostring (); list. add (STA) ;}} bindingsource BS = new bindingsource (); BS. datasource = List; this. listright. datasource = BS; this. listright. displaymember = "name"; this. listright. valuemember = "stcd ";}1-3: After setting the datasource attribute, the item set cannot be modified and can only be bound to the list set. I don't know if there is a good solution, the root cause is that data sources cannot be used to bind data. Only the final version 0.0 of Item 1-4 can be directly added.
# Add listboxitemslistbox to the right of region. selectedobjectcollection selectobj = This. listleft. selecteditems; foreach (model. sta item in selectobj) {bool B = true; // if you want to check whether this item already exists in listright, no foreach (model is added. sta rightitem in this. listright. items) {If (rightitem. name = item. name) {B = false ;}}if (B) {sta = new sta (); Sta. stcd = item. stcd; Sta. name = item. name; this. listright. items. add (STA) ;}} this. listright. displaymember = "name"; this. listright. valuemember = "stcd"; # endregion // Delete the added item on the left // 1-2: remove the selected item int icount = listleft. selecteditems. count; For (INT I = 0; I <icount; I ++) {This. listleft. items. remove (listleft. selecteditems [icount-1-I]);}
Several questions about ListBox