How to set SelectedValue of DropDownList in a GridView

I see many people coming across same issue of how to set the SelectedValue of a DropDownList that is inside of a GridView.

Say this is my GridView bound to a SqlDataSource that get’s the products details. There is Categories DropDownList used to display the Category of the product but the field returned is CategoryID. So I want to use that field to set the SelectedValue of the Categories DropDownList.

<asp:GridView ID="GridView1" runat="server" Width="300px" AutoGenerateColumns="False" DataKeyNames="ProductID,CategoryID" DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound">
      <Columns>
            <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
            <asp:TemplateField HeaderText="Category" SortExpression="CategoryID">
                <ItemTemplate>
                    <asp:DropDownList DataSourceID="SqlDataSource4" ID="DdlCategories" DataTextField="CategoryName" DataValueField="CategoryID" runat="server" SelectedValue='<%# Bind("CategoryID") %>'></asp:DropDownList>
                    <asp:SqlDataSource ID="SqlDataSource4" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT [CategoryID], [CategoryName] FROM [Categories]"></asp:SqlDataSource>
                </ItemTemplate>
            </asp:TemplateField>
      </Columns>
</asp:GridView>

There are several different ways as listed below.

Bind in Markup

As shown in the code above, you can set the SelectedValue by directly binding the CategoryID in the markup like:

SelectedValue='<%# Bind("CategoryID") %>'

Set the value in Code-Behind

That might not work all the time. Say your dropdownlist is databound in code-behind based on some other GridView field. In that case you can set the value in your RowDataBound like shown below:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType== DataControlRowType.DataRow)
    {
        DataRowView drv = e.Row.DataItem as DataRowView;
        DropDownList ddlCategories = e.Row.FindControl("DdlCategories") as DropDownList;
        if(ddlCategories != null)
        {
            //Get the data from DB and bind the dropdownlist
            ddlCategories.SelectedValue = drv["CategoryID"].ToString();
        }
    }
}

When  doing in code-behind, you can use a HiddenField or DataKeys as well to get the CategoryID, but I prefer the DataRowView method.

This should also work when you are trying to Edit a GridView and your dropdownlist is in the EditItemTemplate.

Hope this helps.

No Comments