【问题标题】:getting null value in dropdownlist on rowdatabound event using gridview使用gridview在rowdatabound事件的下拉列表中获取空值
【发布时间】:2014-02-05 05:10:06
【问题描述】:

我收到错误:-"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();               
    }
}

【问题讨论】:

  • 我们是否必须猜测错误发生在哪一行?我猜 FindControl 正在返回 null。
  • 我认为您在 ddllist 中得到空值。

标签: c# asp.net gridview


【解决方案1】:

这样试试

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

(或)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-24
    • 2018-04-16
    • 2010-09-12
    • 2013-03-14
    • 2011-05-24
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多