使用gridview在rowdatabound事件的dropdownlist中获取null值

时间:2014-02-05 05:10:06

标签: c# asp.net gridview

我收到错误: - "Object reference not set to an instance of an object."

当我想将数据绑定到dropdownlist时,这会给我错误。 这是我的代码:

protected void EventRequirementGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
         DropDownList ddllist = (DropDownList)e.Row.FindControl("modeldropdownlist");

         ddllist.SelectedValue = DataBinder.Eval(e.Row.DataItem, "exammode").ToString();               
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个

protected void EventRequirementGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow && && e.Row.RowState == DataControlRowState.Edit)
    {                     
           DropDownList ddllist = (DropDownList)e.Row.FindControl("modeldropdownlist");
           ddllist.SelectedValue = DataBinder.Eval(e.Row.DataItem, "exammode").ToString();               
    }
}

<强>(OR)

 protected void EventRequirementGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow && && e.Row.RowState == DataControlRowState.Edit)
        {
           if ((e.Row.RowState & DataControlRowState.Edit) > 0)
            {            
               DropDownList ddllist = (DropDownList)e.Row.FindControl("modeldropdownlist");
               ddllist.SelectedValue = DataBinder.Eval(e.Row.DataItem, "exammode").ToString();               
            }
         }
    }

或者,您可以使用GridView的PreRender事件从EditItemTemplate访问控件,如:

protected void GridView1_PreRender(object sender, EventArgs e) 
{
  if (GridView1.EditIndex != -1) 
  {
     //Just changed the index of cells based on your requirements
     DropDownList ddllist = (DropDownList)e.Row.FindControl("modeldropdownlist");
     ddllist.SelectedValue = DataBinder.Eval(e.Row.DataItem, "exammode").ToString();              
  }
}