主要是为了识别性别这一列
在GridView编辑列把绑定项转化成模板,然后加入DDL(缩写),具体代码如下:
void bind()
{
using (SqlConnection con = new SqlConnection(conStr))
{
using(SqlDataAdapter sda=new SqlDataAdapter("select * from student ",con))
{
DropDownList ddl;
con.Open();
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataKeyNames = new string[] { "id" };
GridView1.DataBind();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
DataRowView drv = dt.DefaultView[i];
if (Convert.ToString(drv["sex"]) == "男")
{
ddl = (DropDownList)GridView1.Rows[i].FindControl("ddlSex");
ddl.SelectedIndex = 0;
}
else
{
ddl = (DropDownList)GridView1.Rows[i].FindControl("ddlSex");
ddl.SelectedIndex = 1;
}
}
}
}
}
其中ddl中已经有项“男”和“女”,索引分别是0和1