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