在行数据绑定

时间:2016-08-22 14:11:25

标签: c# asp.net list dropdown

我正在尝试绑定网格中的下拉列表,但是我收到了错误。

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

1 个答案:

答案 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";