日期:2014-05-18  浏览次数:20442 次

为什么找不到动态加载的控件呢?
源代码:
Protected   Sub   Page_Load(ByVal   sender   As   Object,   ByVal   e   As   System.EventArgs)   Handles   Me.Load
      If   Not   Page.IsPostBack   Then
            Dim   tRow   As   New   TableRow()
            Dim   tCell   As   New   TableCell()
            Dim   TextBox1   As   New   TextBox()
            tCell   =   New   TableCell()
            TextBox1   =   New   TextBox()
            TextBox1.ID   =   "WellName "
            TextBox1.Width   =   100
            TextBox1.Text   =   "WellName "
            tCell.Controls.Add(TextBox1)
            tRow.Cells.Add(tCell)
            BedData.Rows.Add(tRow)
      Else
            Dim   MyControl   As   Control   =   BedData.FindControl( "WellName ")
            If   (Not   MyControl   Is   Nothing)   Then
                    Dim   WellName   As   String   =   MyControl.ToString
            Else
                    Response.Write( "没找到 ")
            End   If
      End   If
End   Sub
其中:BedData为Table控件

------解决方案--------------------
在行里面去找
------解决方案--------------------
用Page.FindControl( "WellName ")来查找吧
------解决方案--------------------
返回的时候页面重新加载了,而这个控件在加载的时候又不会重新生成,肯定会不存在的
想想其他办法
------解决方案--------------------
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim tRow As New TableRow()
Dim tCell As New TableCell()
Dim TextBox1 As New TextBox()
tCell = New TableCell()
TextBox1 = New TextBox()
TextBox1.ID = "WellName "
TextBox1.Width = 100
TextBox1.Text = "WellName "
tCell.Controls.Add(TextBox1)
tRow.Cells.Add(tCell)
BedData.Rows.Add(tRow)

Dim MyControl As Control = BedData.FindControl( "WellName ")
If (Not MyControl Is Nothing) Then
Dim WellName As String = MyControl.ToString
Else
Response.Write( "没找到 ")
End If
End Sub

------解决方案--------------------
在page_load事件动态创建控件的话都不要放在Not IsPostBack里面

动态创建的需要每次都创建,不然NOT IsPostBack的时候没有创建控件,当然就找不到了
------解决方案--------------------
你可以点击按钮的时候把值记录下来,等到重新刷新的时候再把值赋回去。。