1

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?

Jenda Matejicek
  • 151
  • 3
  • 14

1 Answers1

1

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 
    }
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • It works, but after confirm edit it throws exception: `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. ` - How could I Bind that column value? – Jenda Matejicek Aug 30 '13 at 10:25
  • @Jenda: That seems to be a different question because it is about the update statement and not the databind issue in this question. So you should ask another question and show the relevant code(incl. sql and database schema). – Tim Schmelter Aug 30 '13 at 10:29
  • Ok... Thank you, I'll make another question ;) – Jenda Matejicek Aug 30 '13 at 10:33