我们在数据库中有一个student数据表:
注:studentSex为Bit类型,其中1代表男,0代表女
在GridView中显示情况:
我们在选择Edit后,需要在Sex列中以DropDownList形式展现,并且展现的DropDownList的默认选项当前学生的性别。如图所示:
Sex列代码:
1 < asp:TemplateField HeaderText = " Sex " > 2 < EditItemTemplate > 3 & nbsp; < asp:DropDownList ID = " sex " runat = " server " > 4 </ asp:DropDownList > 5 </ EditItemTemplate > 6 < ItemTemplate > 7 < asp:Label ID = " Label1 " runat = " server " Text = ' <%# Convert.ToBoolean(Eval("studentSex"))?"男":"女" %> ' ></ asp:Label > 8 </ ItemTemplate > 9 < HeaderStyle Width = " 50px " /> 10 </ asp:TemplateField >
后台代码:
1 protected void GridView1_RowDataBound( object sender, GridViewRowEventArgs e) 2 { 3 bool sex = Convert.ToBoolean(DataBinder.Eval(e.Row.DataItem, "studentSex")); 4 if (e.Row.Cells[2].FindControl("sex") != null) 5 { 6 DropDownList ddl = (DropDownList)e.Row.Cells[2].FindControl("sex"); 7 ListItem li1=new ListItem("男","1"); 8 if (sex) 9 { 10 li1.Selected = true;11 }12 ddl.Items.Add(li1);13 ListItem li2 = new ListItem("女", "0");14 if (!sex)15 { 16 li2.Selected = true;17 }18 ddl.Items.Add(li2);19 }20 }