Damn bad controls.
Bind it to a data source, such as list <t> and arraylist.
When you add or delete data from such data sources, The ListBox control will not synchronize with the data source.
The grid control is automatically synchronized.
At this time, if you call ListBox. Items. Add (item), the system will give "cannot modify data items after setting the data source ". This method cannot be called.
In this way, it is difficult for you to move data items up and down.
Solution 1:
Redefine a list, and assign values to the original number. Then it is associated with ListBox. datasoure. You can synchronously Update The ListBox view.
List orgin = new list ();
List. Add (item );
List. Add (item );
List. Add (item );
ListBox. datasource = orgin.
Orgin. Add (item2 );
// At this time, The ListBox will not be updated synchronously.
List newdatasource = new list ();
List. addrange (orgin );
ListBox. datasource = newdatasouse.
// You can synchronize updates.
Solution 2:
Use bindingsource as the intermediary.
Using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. Data;
Using system. drawing;
Using system. LINQ;
Using system. text;
Using system. Windows. forms;
Using system. collections;
Using mylistcontrolsample;
namespace windowsformsapplication2
{< br> Public partial class form3: Form
{< br> private arraylist usstates;
Public form3 ()
{< br> initializecomponent ();
usstates = new arraylist ();
usstates. add (New usstate ("Alabama", "Al");
usstates. add (New usstate ("Washington", "wa");
usstates. add (New usstate ("West Virginia", "WV");
usstates. add (New usstate ("Wisconsin", "Wi");
usstates. add (New usstate ("Wyoming", "WY");
bindingsource BS = new bindingsource ();
BS. datasource = usstates;
This. listbox1.datasource = BS;
}
Private void buttonremove_click (Object sender, eventargs E)
{
Usstate temp = (usstate) This. listbox1.selecteditem;
Usstates. Remove (temp );
Bindingsource BS = new bindingsource ();
BS. datasource = usstates;
This. listbox1.datasource = BS;
}
Private void buttonadd_click (Object sender, eventargs E)
{
Usstates. Add (New usstate ("Ouyang", "Viola "));
Bindingsource BS = new bindingsource ();
BS. datasource = usstates;
This. listbox1.datasource = BS;
}
Private void buttonmoveup_click (Object sender, eventargs E)
{
Int Index = This. listbox1.selectedindex;
If (Index = 0)
{
Return;
}
Int up = index-1;
Usstates [Index] = usstates [Up];
Usstates [Up] = This. listbox1.selecteditem;
Bindingsource BS = new bindingsource ();
BS. datasource = usstates;
This. listbox1.datasource = BS;
This. listbox1.clearselected ();
This. listbox1.selecteditem = usstates [Up];
}
}
}