How to show original DropDownList selected items in GridView RowUpdating event

2018-11-05 c# gridview

I have GridView columns which I'd like to update using RowUpdating event. To do that, I use a dropdownlist in the GridView EditItemTemplate and it works perfectly.

However there's a problem when I enter GridView edit mode; the selected item in dropdownlist is showing its default value, not the previously selected items which is stored in the database. So if a user is editing a different column & overlook the dropdownlist , the GridView column (with the dropdownlist in EditItemTemplate) will be wrongly updated to the dropdownlist default value.

In other words, as I enter GridView edit mode I want the dropdownlist to show (or select) a value binded to my SQL database and not showing its default or first value. I tried using <%# Bind("zone") %>' which works for a textbox but it won't work for dropdownlist. Any idea?

Here's my GridView code:

<asp:GridView ID="GridView1" runat="server" 
    DataKeyNames="ID" AllowSorting="False"  
        <asp:TemplateField HeaderText="Zone" SortExpression="Zone">
                <asp:DropDownList ID="ddlZone" runat="server" Width="80px">
                    <asp:ListItem Value="zone1">Zone 1</asp:ListItem>
                    <asp:ListItem Value="zone2">Zone 2</asp:ListItem>
                    <asp:ListItem Value="zone3">Zone 3</asp:ListItem>
                <asp:Label ID="lblZone" runat="server" Text='<%# Bind("zone") %>'></asp:Label>
        <asp:TemplateField HeaderText="Subzone" SortExpression="Subzone">
                <asp:TextBox ID="txtSubzone" runat="server" Text='<%# Bind("subzone") %>' Width="100px"></asp:TextBox>
                <asp:Label ID="lblSubzone" runat="server" Text='<%# Bind("subzone") %>'></asp:Label>

Code behind:

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

    string textZone = (GridView1.Rows[e.RowIndex].FindControl("ddlZone") as DropDownList).SelectedItem.Value;
    string textSubzone = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtSubzone")).Text;

    string query = "UPDATE tblRegion SET zone = '" + textZone
        + "', subzone ='" + Subzone"
        + "' WHERE (ID ='" + entryID + "')";

    SqlCommand sqlCmd = new SqlCommand(query, conn);
    SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

    DataTable dt = new DataTable();

Thanks in advance :-)


If your list is always static this should work.

<asp:DropDownList ID="ddlZone" runat="server" Width="80px" SelectedValue='<%# Bind("zone") %>'>

If for some reason it doesn't then you can try setting the selected value from code behind OnDataRowBound event.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        if (e.Row.RowState == DataControlRowState.Edit)
            var ddl = (DropDownList) e.Row.FindControl("ddlZone");
            ddl.SelectedValue = "zone1"; //Your logic to bind the requiered index or value