我有一个专门用该ShowDialog
方法显示的表单。在这种情况Form_Shown
下,我会根据调用表单中的公共变量集动态创建一组标签和文本框。
我知道表单没有关闭或销毁,而只是在调用之间隐藏,因此我在Form_Shown
事件顶部添加了代码以清除先前调用中的任何控件,但控件没有被删除。我已经尝试过ctrl.Dispose
(如下面的代码)和Me.Controls.Remove(ctrl)
. 两者都不会产生错误,但不会删除文本框并在其上创建新的文本框。(由于某些原因,
这是我第一次在 .NET 中动态创建/删除控件,因此我对 VB6 控件数组的向往可能与该错误有关。
表单基于调用表单的公共 ListView 变量自行构建。调用表单确保该变量不是空的,并且当且仅当用户正在编辑现有行时才选择项目。
Public Class frmTableEdit
Private isNew As Boolean
Private inputText() As TextBox
Private Sub FormTableEdit_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
For Each ctrl As Control In Me.Controls
If TypeOf (ctrl) Is TextBox Or TypeOf (ctrl) Is Label Then
ctrl.Dispose()
End If
Next
With frmKioskData.TBLobj
Dim fieldCount As Integer = .Columns.Count - 1
isNew = .SelectedIndices.Count = 0
'(code setting size of form and location of OK/Cancel buttons is here)
ReDim inputText(fieldCount)
For i As Integer = 0 To fieldCount
Dim lbl As New Label, txt As New TextBox
inputText(i) = txt
Me.Controls.Add(lbl)
Me.Controls.Add(txt)
'(code setting size and and position of lbl & txt is here)
'lbl.Tag = i (I commented these lines out because I never used the
'txt.Tag = i Tag property, but can if a solution calls for it.)
lbl.Text = .Columns(i).Text
If isNew Then
txt.Text = ""
Else
txt.Text = .Items(.SelectedIndices(0)).SubItems(i).Text
End If
Next
End With
End Sub
End Class