这是因为数据表中的 parentId是空的,而绑定的数据源sdsModule是有值的,没有空值,也就说没有对应项,所以就报错了。
<asp:TemplateField HeaderText="父模块">
<ItemTemplate><asp:Label ID="labParentId" runat="server" Text='<%#Eval("parentId") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="parentList" DataSourceID="sdsModule" DataTextField="moduleName" DataValueField="moduleId" SelectedValue='<%#Eval("parentId") %>'>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
既然没有空值,那就加个空行。想到两种方案:
1. 在GridView1_RowDataBound中加个空列表?
2. 在 GridView1_RowCreated中加个空列表?
试了一下,都不行。RowCreated时,数据源还没加载完,就要SelectedValue='<%#Eval("parentId") %>'操作,还是报错。
既然前台不行,就只能改成后台了。去掉SelectedValue='<%#Eval("parentId") %>',如下:
<asp:TemplateField HeaderText="父模块">
<ItemTemplate>
<asp:Label ID="labParentId" runat="server" Text='<%#Eval("parentId") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="parentList" DataSourceID="sdsModule" DataTextField="moduleName" DataValueField="moduleId" >
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
在RowDataBound事件中找到DropDownList 并赋值:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
DropDownList dtp = (DropDownList)e.Row.FindControl("parentList");
dtp.Items.Insert(0, new ListItem("--请选择--", ""));
string strParentId = this.GridView1.DataKeys[e.Row.RowIndex]["parentId"].ToString();
dtp.SelectedValue = strParentId;
}
}
}
本文介绍了解决ASP.NET中DropDownList控件在绑定数据时遇到空值导致的错误问题。通过移除前台绑定SelectedValue的方式,并在RowDataBound事件中动态设置DropDownList的值,实现了对空值的有效处理。
130

被折叠的 条评论
为什么被折叠?



