This may seem like a duplicate question but I don't think it is. I'm setting up my asp:DropDownList
in the ASPX page and setting it's SelectedValue
during the RowDataBound
event after checking if the current gridview row is the being edited. No errors are thrown when I set the SelectedValue
property of the control and when I check it immediately after setting it, it hasn't changed.
Here's the relevant code
<asp:SqlDataSource
ID="DataSourceAnswerGroups"
runat="server"
ConnectionString="<%$ ConnectionStrings %>"
DataSourceMode="DataSet"
SelectCommand="
SELECT
Id
,Description
FROM dbo.table
WHERE Active = 1
ORDER BY Description
;
" />
<asp:GridView
ID="GridView"
runat="server"
OnRowDataBound="GridView_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Answer Group" SortExpression="AnswerGroup" ItemStyle-Wrap="false" ItemStyle-CssClass="left">
<ItemTemplate>
<%# Eval("AnswerGroup") %>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList
ID="ddlAnswerGroupEdit"
runat="server"
DataSourceID="DataSourceAnswerGroups"
DataValueField="Id"
DataTextField="Description"/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex == GridView.EditIndex)
{
DropDownList ddlAnswerGroupEdit = (DropDownList)e.Row.FindControl("ddlAnswerGroupEdit");
ddlAnswerGroupEdit.SelectedValue = GridView.DataKeys[e.Row.RowIndex].Values["AnswerGroupId"].ToString();
Response.Write(GridView.DataKeys[e.Row.RowIndex].Values["AnswerGroupId"].ToString() + "<br/>"); // this outputs the correct guid
Response.Write(ddlAnswerGroupEdit.SelectedValue + "<br/>"); // this always outputs the same guid, the one that represents the first item on the list.
}
}
There are no other manipulations of the DdataSource or the DropDownList anywhere in the code. The default selection should be changing but it is silently failing. Any help would be appreciated.
Of all the stupid issues to have. This didn't fix it but it did get me going in the right direction. It was a case sensitivity issue. The SQL Server was returning the guiid in uppercase and the control items were in lowercase. This is the only fix I had to make:
ddlAnswerGroupEdit.SelectedValue = GridView.DataKeys[e.Row.RowIndex].Values["AnswerGroupId"].ToString().ToLower();