views:

3854

answers:

3

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...

+2  A: 

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
}
Jason
I think you also don't need (e.Row.RowType == DataControlRowType.DataRow) unless you've hacked editable header rows in somehow.
quillbreaker
no you do because it starts w/the header row and works its way down. you get an error if you don't do this, or it just doesn't function.
Jason
A: 

I am also having the same problem....i can bind the dropdownlist in the edit item template..The drop down list is having null values.

protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e) { DropDownList drpBuildServers = new DropDownList();

    if (grdDevelopment.EditIndex == e.Row.RowIndex)
    {
        drpBuildServers = (DropDownList)e.Row.Cells[0].FindControl("ddlBuildServers");
    }

}

also getting an error

Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.

A: 

protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e) { if (grdDevelopment.EditIndex == e.Row.RowIndex && e.Row.RowType==DataControlRowType.DataRow) {
DropDownList drpBuildServers = (DropDownList)e.Row.Cells[0].FindControl("ddlBuildServers"); } }

Try this one

This will help u