When binding data, we usually bind a field of a table to the dropdownlist. We use the jobs table of the pubs database as an example. We will display the job_desc field when displaying the data, bind the values value to the job_id field.
Method 1:
Using attribute settings, we add a column as a blank row in the items attribute of dropdownlist, and then change the appandbatabunditems attribute to true.
Binding code: Code
1 sqlconnection conn = new sqlconnection ("Server =.; uid = sa; database = pubs ");
2 sqldataadapter DAP = new sqldataadapter ("select * from jobs", Conn );
3 datatable dt = new datatable ();
4 DAP. Fill (DT );
5 dropdownlist1.items. Clear ();
6 dropdownlist1.datasource = DT;
7 dropdownlist1.datatextfield = "job_desc ";
8 dropdownlist1.datavaluefield = "job_id ";
9 dropdownlist1.databind ();
In this way, you can.
Method 2:
Code:
Code
1 sqlconnection conn = new sqlconnection ("Server =.; uid = sa; database = pubs ");
2 sqldataadapter DAP = new sqldataadapter ("select * from jobs", Conn );
3 datatable dt = new datatable ();
4 DAP. Fill (DT );
5 dropdownlist1.items. Clear ();
6 dropdownlist1.datasource = DT;
7 dropdownlist1.datatextfield = "job_desc ";
8 dropdownlist1.datavaluefield = "job_id ";
9 dropdownlist1.databind ();
10 dropdownlist1.items. insert (0, new listitem ("", ""); // insert an empty entry, which must be placed after data binding
Effect: