asp.netselectedvalueedititemtemplate

ASP.Net DropDownList selected value missing


At the beginning I have to say that I tried to find the answer... And yes I'm new in ASP.Net world :)

I would like to use DropDownList in an EditItemTemplate field in GridView. I found I cannot set parametr SelectedValue. It's missing. When I try to set it in code behind it seems to ddlEditPermissions doesn't exists.

<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>

I'm really confused. Could anyone advise me?


Solution

  • You can use RowDataBound of the GridView which gets triggered for every GridViewRow after it was constructed and databound:

    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 
        }
    }