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

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

About Peter Kellner

Follow me:


Comments

  1. Thanks a lot 🙂

  2. Awesome! 😀

    thankyouthankyouthankyou

  3. Dear,

    thanks for that article, I’m having a similar problem with a FormView where I’d like to use a DropDownList to insert new Values.

    When the “SelectedValue” is not taken and inserted in the field, may this be caused by the same issue? Can you help me solving?

    Rgds

Follow

Get every new post delivered to your Inbox

Join other followers: