How to bind a DropDownList in a GridView in the EditItemTemplate Field

asp.netdata-bindinggridview

Here's my code in a gridview that is bound at runtime:

...
<asp:templatefield>
    <edititemtemplate>
        <asp:dropdownlist runat="server" id="ddgvOpp" />
    </edititemtemplate>
    <itemtemplate>
        <%# Eval("opponent.name") %>
    </itemtemplate>
</asp:templatefield>
...

I want to bind the dropdownlist "ddgvOpp" but i don't know how. I should, but I don't. Here's what I have, but I keep getting an "Object reference" error, which makes sense:

protected void gvResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow) //skip header row
    {
        DropDownList ddOpp = (DropDownList)e.Row.Cells[5].FindControl("ddgvOpp");
        BindOpponentDD(ddOpp);
    }
}

Where BindOpponentDD() is just where the DropDownList gets populated. Am I not doing this in the right event? If not, which do I need to put it in?

Thanks so much in advance…

Best Answer

Ok, I guess I'm just dumb. I figured it out.

In the RowDataBound event, simply add the following conditional:

if (myGridView.EditIndex == e.Row.RowIndex)
{
     //do work
}
Related Topic