Bind Data to DropDownList in GridView asp.net

asp.net

I have web form with a GridView and a few controls in the GridView. I have a DropDownList in the EdtItemTemplate of the gridview.

I am needing to bind this DropDownList with some method in my CodeBehind File that returns a Array of type LisItems.

The problem I am facing is this. Since the Control is sitting in the EditItemTemplate, using the FindControl("MyControlID") does not seem to work in any of the GridView events, it returns null, in other words it cannot seem to find the control, unless I use the OnRowUpdating event, but I cannot use this event as the Control needs to be Data binded before that.

Is there anyway I can use the <%# Bind("MyMethodName") %> to bind the control?

Best Answer

Try this

Create a class of your data in App_Code, Like this

public static class Fruits
{
    public static List<string> GetFruits()
    {
        return new string[] { "Apple", "Mango", "Banana", "Grapes" }.ToList();
    }
}

Add a grid to your page, Which I guess you all ready have

<asp:GridView runat="server" ID="grid" AutoGenerateColumns="false" OnRowEditing="grid_RowEditing">
        <Columns>
            <asp:TemplateField HeaderText="Selected Fruit">
                <ItemTemplate>
                    <asp:Label runat="server" ID="Fruit" Text='<%# Eval("Fruits") %>' />
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:DropDownList runat="server" ID="fruits" DataSourceID="fruitsDS" />
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Edit">
                <ItemTemplate>
                    <asp:Button runat="server" ID="btnEdit" Text="Edit" CommandName="Edit" />
            </ItemTemplate>
      </asp:TemplateField>
    </Columns>
</asp:GridView>

And add an Object Datasource to bind your DropDowns of edit template

<asp:ObjectDataSource ID="fruitsDS" runat="server" SelectMethod="GetFruits" TypeName="Fruits" />

Hope this could help.