Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you bind a DropDownList in a GridView in the EditItemTemplate Field?

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

like image 509
Jason Avatar asked Oct 05 '08 15:10

Jason


People also ask

How do you show records in a GridView using DropDownList in web application?

Create Database Now, take an ASP.NET web application -> Take one DropDownList control and one GridView control. Your form will look as in the following figure. Now set the AutoPostBack property of the DropDownList to "True".

What is EditItemTemplate in GridView in ASP NET?

Add an EditItemTemplate in the TemplateField that specifies a custom user interface (UI) for the item in edit mode. Set the Command name property to Edit in the Edit button, Update in the Update button and Cancel in the Cancel Button depending on their respective Events.


2 Answers

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
}
like image 145
Jason Avatar answered Oct 19 '22 23:10

Jason


Thanks to Saurabh Tripathi,

The solution you provided worked for me. In gridView_RowDataBound() event use.

if(gridView.EditIndex == e.Row.RowIndex && e.Row.RowType == DataControlRowType.DataRow)
{
    // FindControl
    // And populate it
}

If anyone is stuck with the same issue, then try this out.

Cheers.

like image 21
Amol Avatar answered Oct 20 '22 00:10

Amol