1. If the item is displayed statically in the drop-down form, you can edit it by setting the items attribute of ComboBox.
2. You can also dynamically display items, that is, read the items to be displayed from the database.
Method shown in the book: use dataset to fill Code
Using System. Data;
Using System. drawing;
Using System. text;
Using System. Windows. forms;
Using System. Data. sqlclient;
NamespaceSep16test
{
Public Partial ClassForm1: Form
{
PublicForm1 ()
{
Initializecomponent ();
}
Private Void Form1_load ( Object Sender, eventargs E)
{
This . Combobox1.items. Clear ();
String Connstring = @" Server = localhost; Integrated Security = true; database = test " ;
Sqlconnection thisconnection = New Sqlconnection (connstring );
String Strsql = " Select distinct username from testtable " ;
Sqldataadapter thisadapter = New Sqldataadapter (strsql, thisconnection );
Dataset thisdateset = New Dataset ();
Thisadapter. Fill (thisdateset );
This . Combobox1.beginupdate ();
This . Combobox1.datasource = Thisdateset. Tables [ 0 ];
This . Combobox1.displaymember = " Username " ;
This . Combobox1.valuemember = " Username " ;
This . Combobox1.endupdate ();
}
}
}
You can use the beginupdate () method to prevent re-drawing the ComboBox every time you add an item to the items. After the task of adding an item to the List is completed, call the endupdate () method to re-draw the ComboBox. when a large number of items are added to the list, this method can be used to prevent flickering when ComboBox is drawn.
?? The database connection is not enabled here. Why can the database value be obtained? Does dataadapter need to open a connection?
Sample dataadapter provided on msdn: Code
Private Static Dataset selectrows (Dataset dataset,
String Connectionstring, String Querystring)
{
Using (Sqlconnection connection =
New Sqlconnection (connectionstring ))
{
Sqldataadapter Adapter = New Sqldataadapter ();
Adapter. selectcommand = New Sqlcommand (
Querystring, connection );
Adapter. Fill (Dataset );
Return Dataset;
}
}
It does not seem necessary.
Another method for dynamically binding ComboBox items found on the Internet: Using datareader Code
String Connstring = @" Server = localhost; Integrated Security = true; database = test " ;
Sqlconnection thisconnection = New Sqlconnection (connstring );
String Strsql = " Select distinct userid, username, sex, place from testtable " ;
Sqlcommand thiscommand = New Sqlcommand (strsql, thisconnection );
Thisconnection. open ();
Sqldatareader thisreader = Thiscommand. executereader ();
If (Thisreader. hasrows) // The hasrows attribute is used to obtain a value indicating whether the sqldatareader contains one or more rows. True if sqldatareader contains one or more rows; otherwise, false.
{
Combobox1.items. Clear (); // Clear ComboBox
While (Thisreader. Read ())
{
Combobox1.items. Add (thisreader [ 1 ]. Tostring ()); // Read data cyclically
}
Thisconnection. Close ();
}