Search code examples
c#asp.netfindcontrol

FindControl in RowDataBound-Event ends in error


My TemplateField in my GridView was created like this:

<asp:TemplateField HeaderText="Dienstleistung" SortExpression="gutscheinbezeichnung" HeaderStyle-Width="20px">
          <EditItemTemplate>
              <asp:HiddenField runat="server" Value='<%# Bind("gutscheinart_id")%>' ID="HiddenFieldGutscheinartID"/>
              <asp:DropDownList ID="DropDownListDienstleistung" ClientIDMode="Static" runat="server" DataSourceID="ObjectDataSourceDropDown" DataValueField="gutscheinbezeichnung">

              </asp:DropDownList>

          <asp:ObjectDataSource ID="ObjectDataSourceDropDown" runat="server" SelectMethod="GetGutscheinArt" TypeName="Gmos.Halbtax.Admin.Client.WebGui.DataManager"></asp:ObjectDataSource>

          </EditItemTemplate>
              <ItemTemplate>
                  <asp:Label ID="LabelGutscheinbezeichnung" runat="server" Text='<%# Bind("gutscheinbezeichnung") %>'></asp:Label>
              </ItemTemplate>
          <HeaderStyle Width="20px" />
</asp:TemplateField>

As you can see, i have a DropDownList called DropDownListDienstleitung in my EditItemTemplate-Field.

I also created this Event:

protected void GridViewLehrling_RowDataBound(object sender, GridViewRowEventArgs e)
{
    DropDownList DropDownListDienstleistungBackEnd = (DropDownList)GridViewLehrling.Rows[GridViewLehrling.SelectedIndex].FindControl("DropDownListDienstleistung");
    HiddenField HiddenFieldGutscheinartIDBackEnd = (HiddenField)GridViewLehrling.Rows[GridViewLehrling.EditIndex].FindControl("HiddenFieldGutscheinartID");
}

Now, if this event fires. This Error occurrs:

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

Any Suggestions?


Solution

  • Try using the following piece of code:

    protected void GridViewLehrling_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.RowState == DataControlRowState.Edit)
            {
                DropDownList ddlBackEnd = (DropDownList)e.Row.FindControl("DropDownListDienstleistung");
                HiddenField hdnBackEnd = (HiddenField)e.Row.FindControl("HiddenFieldGutscheinartID");
            }           
        }
    }
    

    The code first checks the type of the row. It has to be DataRow so that footer and header rows are excluded. Then the code checks if the row is actually in edit mode. If this is the case then the code fetches the controls doing a FindControl on the actual row.