将asp.net中的下拉列表绑定到项目模板的行绑定中

本文关键字:绑定 项目 下拉列表 asp net | 更新日期: 2023-09-27 18:03:22

我正在尝试绑定一个下拉菜单,这是在一个网格,但我得到错误。

<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,因为它不存在于项目列表中。

将asp.net中的下拉列表绑定到项目模板的行绑定中

在您的GridView中,您为DropDownList设置了SelectedValue,但是该值在下拉列表中的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";