Can't Find Controls in GridView on Dynamic Controls

拜拜、爱过 提交于 2019-12-20 05:54:29

问题


I have a gridview where I add textboxes to everycell on runtime. However, I can't seem to access those controls using findcontrol

Here is how I add the textboxes to the 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

When I go to find the controls it says they are Nothing :

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

EDIT The problem is that after the textboxes get populated it recreates the textboxes since I have them in row created


回答1:


Use FindControl within the Cell of the Row that you added the Control:

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



回答2:


The dynamically added textbox doesn't exist in fact. Thus, you cannot access or find it. You can add your textbox physically inside the grid TemplateField and set its visibility to false like the code segment below:

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

After that, and if you want, you can find the textbox and toggle its visibility from code behind.



来源:https://stackoverflow.com/questions/33737710/cant-find-controls-in-gridview-on-dynamic-controls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!