.net – Why isn’t the SelectedIndexChanged event firing from a dropdownlist in a GridView

asp.neteventsgridviewnet

I cannot get my SelectedIndexChanged of my dropdownlist to fire. I have the following:

<form id="form1" runat="server">
<div>
<asp:GridView id="grdPoll" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:DropDownList ID="DropDownList1" runat="server" 
                 AutoPostBack="true"
                 OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
                    <asp:ListItem Text="Review" Value="Review" Selected="True">Review</asp:ListItem>
                    <asp:ListItem Text="Level1" Value="lvl1">Send Back to Level1</asp:ListItem>
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

<asp:Label ID="lblCity" runat="server" Text="Label"></asp:Label>  
</div>
</form>

In my code behind I have this:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    this.lblCity.Text = ((DropDownList)sender).SelectedValue;
}

If I put this same ddl outside of the gridview, it fires.

The postback is occurring and the autopostback is set to true. The event just never fires. Why can't I get my event to fire from within the gridview?

Thank you.

Best Answer

Well, this question was asked more than a month ago and may be irrelevant now, but @LFSR was kind enough to edit it recently, it's in the "Active questions" list.

Since it remains unanswered (224 views!), I thought I should give it a go:


The problem is that in the context of a GridView, the DropDownList(referred to hereafter as DDL) is a dynamic control and therefore its events need to be reattached upon Postback.

When this concept is understood, the solution becomes relatively simple :

ASPX:

<asp:DropDownList ID="DDL1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DDL1_SelectedIndexChanged">
  <asp:ListItem Text="Review" Value="Review" Selected="True">Review</asp:ListItem>
  <asp:ListItem Text="Level1" Value="lvl1">Send Back to Level1</asp:ListItem>
</asp:DropDownList>

CS Code:

protected void Page_Load(object sender, EventArgs e)
{
  if(!Page.IsPostBack)
  {
    // Bind the GridView to something.
    DataBindGrid();
  }
}

protected void DDL1_SelectedIndexChanged(object sender, EventArgs e)
{
  this.lblCity.Text = ((DropDownList)sender).SelectedValue;
}

protected void grdPoll_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if(Page.IsPostBack)
  {
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
      DropDownList ddl = e.Row.FindControl("DDL1") as DropDownList;
      if(ddl != null)
      {
        ddl.SelectedIndexChanged += new EventHandler(DDL1_SelectedIndexChanged);
      }
    }
  }
}