无法在动态控件上的GridView中查找控件

时间:2015-11-16 14:26:55

标签: vb.net gridview dynamic-controls

我有一个gridview,我在运行时向每个单元添加文本框。但是,我似乎无法使用findcontrol

访问这些控件

以下是我如何将文本框添加到gridview:

If e.Row.RowType = DataControlRowType.DataRow Then
        For i = 1 To e.Row.Cells.Count - 1

            Dim txtSchedule As New TextBox()

            txtSchedule.ID = "txtSchedule" & i.ToString

           e.Row.Cells(i).Controls.Add(txtSchedule)
        Next
    End If

当我找到控件时,它说它们什么都不是:

GridView1.Rows(0).Cells(cellindex).FindControl("txtSchedule" & cellindex.ToString)

修改 问题是,在填充文本框后,它会重新创建文本框,因为我已将它们创建在行中

2 个答案:

答案 0 :(得分:1)

在您添加控件的行的单元格中使用FindControl:

GridView1.Rows(0).Cells(cellindex).FindControl("txtSchedule" & cellindex.ToString)

答案 1 :(得分:0)

动态添加的文本框实际上并不存在。因此,您无法访问或找到它。您可以在网格 TemplateField 中实际添加文本框,并将可见性设置为 false ,如下面的代码段所示:

<asp:TemplateField>
   <ItemTemplate>
      <asp:Label ID="Label1" runat="server"></asp:Label>                     
      <asp:TextBox ID="TextBox1" runat="server" Visible="False"></asp:TextBox>
   </ItemTemplate>
</asp:TemplateField>

之后,如果需要,您可以找到文本框并从后面的代码切换其可见性。