我正在尝试绑定网格中的下拉列表,但是我收到了错误。
<asp:GridView ID="grdddl" AutoGenerateColumns="false" ShowHeader="false" OnRowDataBound="grdddl_RowDataBound" ShowFooter="true" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="ddlcommtype" SelectedValue='<%#Eval("ComPlanRoleDescr") %>' AutoPostBack="true" OnSelectedIndexChanged="ddlcommtype_SelectedIndexChanged" runat="server"></asp:DropDownList>
<asp:HiddenField ID="hdnid" Value='<%#Eval("ID") %>' runat="server" />
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlcommtypefooter" AutoPostBack="true" OnSelectedIndexChanged="ddlcommtypefooter_SelectedIndexChanged" runat="server"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void grdddl_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlcommtype = (DropDownList)e.Row.FindControl("ddlcommtype");
ddlcommtype.DataSource = listcommtype;
ddlcommtype.DataTextField = "ComPlanRoleDescr";
ddlcommtype.DataValueField = "ID";
ddlcommtype.DataBind();
}
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlcommtype = (DropDownList)e.Row.FindControl("ddlcommtypefooter");
ddlcommtype.DataSource = listcommtype;
ddlcommtype.DataTextField = "ComPlanRoleDescr";
ddlcommtype.DataValueField = "ID";
ddlcommtype.DataBind();
}
}
此代码出错: 'ddlcommtype'有一个SelectedValue,它是无效的,因为它在项目列表中不存在。
答案 0 :(得分:0)
在GridView
中,您为SelectedValue
设置了DropDownList
,但是
在属于DropDownList的ListItem
中找不到该值。
从此行中删除SelectedValue
:
<asp:DropDownList ID="ddlcommtype" SelectedValue='<%#Eval("ComPlanRoleDescr") %>' AutoPostBack="true" OnSelectedIndexChanged="ddlcommtype_SelectedIndexChanged" runat="server"></asp:DropDownList>
如果您确实想使用SelectedValue
,为什么不在DataBind()
后执行此操作?例如:
DropDownList ddlcommtype = (DropDownList)e.Row.FindControl("ddlcommtype");
ddlcommtype.DataSource = listcommtype;
ddlcommtype.DataTextField = "ComPlanRoleDescr";
ddlcommtype.DataValueField = "ID";
ddlcommtype.DataBind();
// Now set the default value:
ddlcommtype.SelectedValue = "InsertValueHere";