C# 使用gridview在rowdatabound事件的dropdownlist中获取空值

C# 使用gridview在rowdatabound事件的dropdownlist中获取空值,c#,asp.net,gridview,C#,Asp.net,Gridview,我收到错误:-“对象引用未设置为对象的实例。” 当我想将数据绑定到dropdownlist中时,这会给我带来错误。 这是我的密码: protected void EventRequirementGridView_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { DropDownList ddllist =

我收到错误:-
“对象引用未设置为对象的实例。”

当我想将数据绑定到
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();               
    }
}
像这样试试

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();               
    }
}
(或)

或者,您可以使用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();              
  }
}

我们必须猜测错误发生在哪一行吗?我猜FindControl正在返回null。我想您在ddllist中看到的是null值。
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();              
  }
}