DropDownList数据绑定第一项为空

来源:互联网 发布:arm v7多核编程 编辑:程序博客网 时间:2024/05/02 16:34
我们在进行数据绑定时通常把一个表的某个字段绑定到DropDownList中,我们以pubs库的jobs表为例子,我们在显示时显示job_desc字段,values值绑定job_id字段。
方法一:
使用属性设置,我们在DropDownList的items的属性中添加一列为空行,然后更改AppandBataBoundItems属性为ture.
绑定代码:
DropDownList数据绑定第一项为空
1DropDownList数据绑定第一项为空SqlConnection conn = new SqlConnection("server=.;uid=sa;database=pubs");
2DropDownList数据绑定第一项为空        SqlDataAdapter dap = new SqlDataAdapter("select from jobs"
conn);
3DropDownList数据绑定第一项为空        DataTable dt = new
 DataTable();
4
DropDownList数据绑定第一项为空        dap.Fill(dt);
5
DropDownList数据绑定第一项为空        DropDownList1.Items.Clear();
6DropDownList数据绑定第一项为空        DropDownList1.DataSource =
 dt;
7DropDownList数据绑定第一项为空        DropDownList1.DataTextField = "job_desc"
;
8DropDownList数据绑定第一项为空        DropDownList1.DataValueField = "job_id"
;
9DropDownList数据绑定第一项为空        DropDownList1.DataBind();

DropDownList数据绑定第一项为空

这样就可以了。
方法二:
使用代码:
 1DropDownList数据绑定第一项为空
 2DropDownList数据绑定第一项为空        SqlConnection conn = new SqlConnection("server=.;uid=sa;database=pubs");
 3DropDownList数据绑定第一项为空        SqlDataAdapter dap = new SqlDataAdapter("select from jobs"
conn);
 4DropDownList数据绑定第一项为空        DataTable dt = new
 DataTable();
 5
DropDownList数据绑定第一项为空        dap.Fill(dt);
 6
DropDownList数据绑定第一项为空        DropDownList1.Items.Clear();
 7DropDownList数据绑定第一项为空        DropDownList1.DataSource =
 dt;
 8DropDownList数据绑定第一项为空        DropDownList1.DataTextField = "job_desc"
;
 9DropDownList数据绑定第一项为空        DropDownList1.DataValueField = "job_id"
;
10
DropDownList数据绑定第一项为空        DropDownList1.DataBind();
11DropDownList数据绑定第一项为空        DropDownList1.Items.Insert(0new ListItem(""""));//插入空项,此举必须放到数据绑定之后
效果:
DropDownList数据绑定第一项为空
0 0
原创粉丝点击