编程语言
首页 > 编程语言> > c# – RowDataBound中的FindControl – 事件以错误结束

c# – RowDataBound中的FindControl – 事件以错误结束

作者:互联网

我的GridView中的TemplateField创建如下:

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

如您所见,我的EditItemTemplate-Field中有一个名为DropDownListDienstleitung的DropDownList.

我也创建了这个活动:

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");
}

现在,如果这个事件发生了.发生此错误:

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

有什么建议?

解决方法:

尝试使用以下代码:

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");
        }           
    }
}

代码首先检查行的type.它必须是DataRow,以便排除页脚和标题行.然后代码检查该行是否实际处于编辑模式.如果是这种情况,那么代码将获取在实际行上执行FindControl的控件.

标签:c,asp-net,findcontrol
来源: https://codeday.me/bug/20190711/1429650.html