【问题标题】:ASP.Net DropDownList selected value missing缺少 ASP.Net DropDownList 选定值
【发布时间】:2013-08-30 08:23:15
【问题描述】:

一开始我不得不说我试图找到答案...是的,我是 ASP.Net 世界的新手 :)

我想在 GridView 的 EditItemTemplate 字段中使用 DropDownList。我发现我无法设置参数 SelectedValue。它不见了。当我尝试在后面的代码中设置它时,似乎 ddlEditPermissions 不存在。

<asp:TemplateField HeaderText="opravneni" SortExpression="opravneni">
<edititemtemplate>
    <asp:DropDownList ID="ddlEditPermissions" runat="server" DataSource='<%# getPermissions() %>' OnPreRender="ddlEditPermissions_PreRender"/>
</edititemtemplate>
<insertitemtemplate>
    <asp:TextBox ID="tbEditPermissions" runat="server" Text='<%# Bind("opravneni") %>'></asp:TextBox>
</insertitemtemplate>
<itemtemplate>
    <asp:Label ID="lEditPermissions" runat="server" Text='<%# Bind("opravneni") %>'></asp:Label>
</itemtemplate>

我真的很困惑。谁能给我建议?

【问题讨论】:

    标签: asp.net selectedvalue edititemtemplate


    【解决方案1】:

    您可以使用GridView 中的RowDataBound,它会在每个GridViewRow 被构造和数据绑定后触发:

    protected void gridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Edit)
        {
            var ddlEditPermissions = (DropDownList)e.Row.FindControl("ddlEditPermissions");
            // bind DropDown manually
            ddlEditPermissions.DataSource = getPermissions();
            ddlEditPermissions.DataTextField = "Permission_Name"; // presumed text-column
            ddlEditPermissions.DataValueField = "Permission_ID";  // presumed id-column
            ddlEditPermissions.DataBind();
    
            DataRowView dr = e.Row.DataItem as DataRowView;  // you might need to change this type, use the debugger then to determine it
            ddlEditPermissions.SelectedValue = dr["Permission_ID"].ToString(); // presumed foreign-key-column 
        }
    }
    

    【讨论】:

    • 它可以工作,但是在确认编辑后它会抛出异常:Cannot insert the value NULL into column 'OPRAVNENI_ID', table 'HelpDeskDB.dbo.USERS'; column does not allow nulls. UPDATE fails. The statement has been terminated. - 我如何绑定该列值?
    • @Jenda:这似乎是一个不同的问题,因为它是关于更新语句而不是这个问题中的数据绑定问题。所以你应该问另一个问题并显示相关代码(包括 sql 和数据库模式)。
    • 好的...谢谢,我再问一个问题;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 2016-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    相关资源
    最近更新 更多