Skip to content

Why can I not Bind to a value on a DropDownList in a GridView with ASP.NET 2.0 or 3.5?

Updated: at 02:12 PM

So, I guess I should have know the answer to why the following does not work.  Basically, the scenario I have is that I have a foreign key column in my GridView that I want to show as a DropDownList of values.  The code below shows me the values in the DropDownList, but when I update it with the "edit" of the GridView row, the value does not get saved.  Here is the code and what it looks like running:

<asp:TemplateField HeaderText="TemplateUsersId" SortExpression="TemplateUsersId">      <EditItemTemplate>
 
       <asp:DropDownList ID="DropDownListUser" runat="server" AutoPostBack="False" DataSourceID="SqlDataSourceUser"
 
            DataTextField="Username" DataValueField="id" SelectedValue='<%# Bind("TemplateUsersId") %>'>
 
         </asp:DropDownList>
 
         ..

Notice that even though I'm using Bind rather than eval, the value does not stick.  Well, we always have a reason so I believe it is not working because SelectedValue only has a Get (it's read only) and the value can not be put back.  So, the solution that works for me is to program the GridView's Updating Row Event.  That is, get the value from the dropdownlist, and set it in the event.  Here is the code that is working for me.

 /// <summary>    /// This Code Gets the value of the DropDownList in the EditItemTemplate.
 
    /// </summary>
 
    /// <param name="sender"></param>
 
    /// <param name="e"></param>
 
    protected void GridViewIncomingUrls_RowUpdating(object sender, GridViewUpdateEventArgs e)
 
    {
 
        DropDownList dropDownListUser = GridViewIncomingUrls.Rows[e.RowIndex].FindControl("DropDownListUser") as DropDownList;
 
        e.NewValues["TemplateUsersId"] = dropDownListUser.SelectedValue;
 
    }

Yee Ha! it works. Hope you don't have to suffer like me and just bump into this solution

Check out the ORM (Object Relational Mapper) PRISMA. The database access method I use in all my projects