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









November 17th, 2008 at 4:18 am
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
November 11th, 2009 at 8:30 pm
Awesome!
thankyouthankyouthankyou
March 21st, 2011 at 7:41 pm
Thanks a lot
January 19th, 2012 at 12:54 pm
Just wanted to say “cheers”. This really saved my bacon. by all accounts this functionality should just work but it seems in come scenarios it just doesn’t. nice solution.