日期:2014-05-18  浏览次数:20482 次

在GridView中获得DropDownIist的问题> <`
在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 失败。
语句已终止。 

这是为什么呢?

------解决方案--------------------
SEX插入空值了所以报错,也就是说你可能没有得到值
------解决方案--------------------
ddl.SelectedValue == null
你要调试一下,看一下上面的

C# code

 ListItem li = ddl.Items.FindByValue(drv["SEX"].ToString()); 
            li.Selected = true;

------解决方案--------------------
你把SEX这个字段为非空,如果为必填字段就给SEX 一个默认值,免得出错

还有就是你的ddl.SelectedValue没有值