在GridView里添加了一个EditItemTemplate,里面绑定一个DropDownList,这样在进入编辑模式的时候有male跟female两项可以选。
为了从DropDownlist控件中选择当前的值,使用RowDataBound事件,代码:
 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowState == DataControlRowState.Edit)
        {
            System.Data.DataRowView drv = (System.Data.DataRowView)e.Row.DataItem;
            DropDownList ddl = (DropDownList)e.Row.Cell[3].FindControl("DropDownList1");
            ListItem li = ddl.Items.FindByValue(drv["SEX"].ToString());
            li.Selected = true;
        }
    }
再用一个RowUpdating事件把DropDownList控件的值添加回GridView:
protected void GridView1_RowUpdating(object sender, GridViewUpdatedEventArgs e)
    {
        GridViewRow gvr = this.GridView1.Rows[this.GridView1.EditIndex];
        DropDownList ddl = (DropDownList)gvr.Cell[3].FindControl("DropDownList1");
        e.NewValues["SEX"] = ddl.SelectedValue;
    }其中DropDownList1绑定的数据源是一个表如下:
female
male结果运行的时候进行编辑就出现了这样的错误:
不能将值 NULL 插入列 'SEX',表 'STUDENT.dbo.student';列不允许有空值。UPDATE 失败。
语句已终止。 这是为什么呢?