The first item of dropdownlist data binding is null.

Source: Internet
Author: User
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:

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.