vb控件
vb的控件数组中如何判断一个控件元素是否已经加载,如果已经加载,索引值加1,如果未加载就加载此元素?
[解决办法]
Private Type clsType
cName As String
ID As Integer
End Type
Private Sub Command1_Click()
Dim iCtl As Control, iCls() As clsType
Dim i As Integer
ReDim iCls(0)
For Each iCtl In Controls
iCls(0).cName = TypeName(iCtl) '取得CTRL名称
For i = 1 To UBound(iCls)
If iCls(i).cName = iCls(0).cName Then
iCls(i).ID = iCls(i).ID + 1 '加入CTRL数量
Exit For 'i
End If
Next 'i
If i > UBound(iCls) Then '未寻获
ReDim Preserve iCls(UBound(iCls) + 1) '加入CTRL
iCls(UBound(iCls)).cName = iCls(0).cName '新增名称
iCls(UBound(iCls)).ID = 1 '加入数量
End If
Next 'iCls
For i = 1 To UBound(iCls)
If iCls(i).cName = "TextBox" Then Exit For '寻获CTRL,离开i
Next 'i
If i > UBound(iCls) Then '未寻获
Set iCtl = Controls.Add("VB.TextBox", "Text1", Me)
' 其它对该物件位移、植入资料...等,就自己加罗
iCtl.Visible = True '最後才显示出来
End If
End Sub
VERSION 5.00
Begin VB.Form Form1
Caption = "Form1"
ClientHeight = 6255
ClientLeft = 60
ClientTop = 345
ClientWidth = 4230
LinkTopic = "Form1"
ScaleHeight = 6255
ScaleWidth = 4230
StartUpPosition = 3 '窗口缺省
Begin VB.CommandButton Command2
Caption = "del"
Height = 375
Left = 1920
TabIndex = 3
Top = 480
Width = 1935
End
Begin VB.TextBox Text1
Height = 375
Index = 1
Left = 0
TabIndex = 2
Text = "3"
Top = 480
Width = 1815
End
Begin VB.CommandButton Command1
Caption = "add"
Height = 375
Left = 1920
TabIndex = 1
Top = 120
Width = 1935
End
Begin VB.TextBox Text1
Height = 375
Index = 0
Left = 0
TabIndex = 0
Text = "3"
Top = 120
Width = 1815
End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Dim colTextbox1 As New Collection
Function TextboxIsLoad(index As Integer) As Boolean
On Error GoTo NotFound
If colTextbox1(CStr(index)) <> -1 Then '添加的时候指定的值都是0,这里用-1判断,等待出错...
TextboxIsLoad = True
End If
Exit Function
NotFound: '出错就是没有这个元素
Err.Clear
TextboxIsLoad = False
End Function
Sub AddTextbox(index)
colTextbox1.Add 0, CStr(index) 'key值就是index了,不能重复
End Sub
Sub RemoveTextBox(index)
colTextbox1.Remove index
End Sub
Private Sub Command1_Click()
If TextboxIsLoad(Text1(0).Text) Then
MsgBox "Loaded textbox(" & Text1(0).Text & ")"
Else
Load Text1(Text1(0).Text)
'添加成功后显示出来,看看效果
Text1(Text1(0).Text).Top = Text1(0).Top + Text1(0).Text * Text1(0).Height: Text1(Text1(0).Text).Visible = True
AddTextbox (Text1(0).Text) '在集合里记录他的index
MsgBox "Didn't Load text1(" & Text1(0).Text & ")" & vbCrLf & "Loading..." & vbCrLf & "Loaded."
End If
End Sub
Private Sub Command2_Click()
If TextboxIsLoad(Text1(1).Text) Then
Unload Text1(Text1(1).Text)
RemoveTextBox (Text1(1).Text)
MsgBox "Text(" & Text1(1).Text & ") deleteing" & vbCrLf & "deleted OK"
Else
MsgBox "No Text1(" & Text1(1).Text & ")"
End If
End Sub
Private Sub Form_Load()
AddTextbox 0 '添加textbox时用于指定添加的index.先把他自己加进去
AddTextbox 1 '删除textbox时用于指定删除的index.先把他自己加进去
End Sub