【发布时间】:2014-01-22 17:36:21
【问题描述】:
我很困惑为什么这不起作用......
以下是我在表单加载时动态声明按钮的简要说明,因为表单会根据所选内容自行调整大小。我已将按钮命名为 button1 和 button2。我已经向 button2 添加了一个处理程序来处理单击按钮时的处理。 GetButtonColl 在按钮创建后被调用,我验证它填充了表单上的按钮。为什么简单的 .enable 属性不适用于这些动态创建的按钮?我需要做些不同的事情吗?
这是我的代码的精简版:
Public buttonColl As New List(Of Button)
'---------------------------------------------------------------------------------------------------------------
' Function: GetButtonColl
' Parameters: none
' Returns: none
' Description: Loops through all the controls on the form and searches for buttons that were created after the form has been resized
' and adds them to a List which will be used to quickly control the buttons properties throughout the session
'----------------------------------------------------------------------------------------------------------------
Public Sub GetButtonColl()
For x As Integer = 0 To Me.Controls.Count - 1
Dim b As Control = TryCast(Me.Controls(x), Control)
If b IsNot Nothing AndAlso b.Tag Is Nothing Then
If TypeOf (b) Is Button Then
buttonColl.Add(b)
End If
End If
Next
End Sub
Public Sub button1_Handler(ByVal sender As Object, ByVal e As System.EventArgs)
Try
For Each bttn As Button In buttonColl
If bttn.Name = "button2" Then
bttn.Enabled = False
End If
Next
Catch ex As Exception
End Try
End Sub
这是我通过代码创建按钮的方式:
btn = New System.Windows.Forms.Button
With btn
.Enabled = true
.Location = New System.Drawing.Point(9, 332)
.Size = New System.Drawing.Size(122, 26)
.Name = "button1"
.Text = "TestButton"
.BackColor = System.Drawing.SystemColors.Control
.Cursor = System.Windows.Forms.Cursors.Default
.Font = New System.Drawing.Font("Arial", 11.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
.ForeColor = System.Drawing.SystemColors.ControlText
.RightToLeft = System.Windows.Forms.RightToLeft.No
.TabIndex = TabIndex
.UseVisualStyleBackColor = False
End With
Me.Controls.Add(btn)
【问题讨论】:
-
button1_Handler没有处理程序(没有处理程序...),所以除非您动态添加处理程序(代码显示无),否则它可能没有运行。添加断点查看。 -
我已调试并确认我为 button1 拥有的处理程序命中了 button1_handler 子例程。我在动态创建 button1 控件的函数中添加了处理程序