2

作为 VB 的新用户,我很难理解为什么这段代码在一个项目中有效,而在另一个项目中无效。如果我创建一个新项目和 2 个新表单,则此代码可以正常工作,但是当我放入我的项目时,左键或右键单击都不会触发。

我尝试了 try/catch 语句,但没有报告错误。我该如何解决这个问题以找出错误。我试图删除代码并在每条评论之后运行,但仍然相同。我什至尝试删除表单上的所有其他代码,只留下 2 个潜艇,但没有任何乐趣。任何帮助将不胜感激。

主界面

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


        'TODO: This line of code loads data into the 'StorageDataSet1.Customers' table. You can move, or remove it, as needed.
        Me.CustomersTableAdapter.Fill(Me.StorageDataSet1.Customers)
        'TODO: This line of code loads data into the 'StorageDataSet.User' table. You can move, or remove it, as needed.
        Me.UserTableAdapter.Fill(Me.StorageDataSet.User)

        'Dim frmDepartmentsLive As New frmDepartment
        'frmDepartmentsLive.Owner = Me
        'frmDepartmentsLive.ShowDialog()


        lblDate.Text = Now

        Timer1.Start()

        rdoCustomer.Enabled = False
        rdoCustomer.Checked = True
        rdoDepartment.Enabled = False
        rdoDepartment.Checked = False

        For Each ctrl In Me.Controls
            If TypeOf ctrl Is Button Then
                AddHandler CType(ctrl, Button).MouseDown, AddressOf btn_MouseDown
            End If
        Next

    End Sub

Private Sub btn_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs)

        If (e.Button = MouseButtons.Right) Then
            Dim btn = CType(sender, Button)
            frmRacks.buttonName = btn.Name.Replace("btn", "")
            frmRacks.Show()
        ElseIf (e.Button = MouseButtons.Left) Then
            MessageBox.Show("To be coded")
        End If
    End Sub

框架架

Public Class frmRacks
    Public buttonName As String
    Private Sub racksfrm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        lblRacks.Text = buttonName

    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub



End Class
4

1 回答 1

1

由于控件位于面板上,因此它们是该面板控件数组的成员,而不是表单的成员。如果您通过表单的设计器(在解决方案资源管理器上,单击 Show All,然后打开formXXX.designer.vb),这 - 以及其他事情 - 是显而易见的。不要改变任何东西,但它显示了控件是如何创建和添加的。所以...

    For Each ctrl In thepanelName.Controls
        If TypeOf ctrl Is Button Then
            AddHandler CType(ctrl, Button).MouseDown, AddressOf btn_MouseDown
        End If
    Next

如果只有面板上的那些按钮,您可以将其缩短:

  For Each btn As Button In thepanelName.Controls
       AddHandler CType(ctrl, Button).MouseDown, AddressOf btn_MouseDown
  Next
于 2013-10-27T15:01:58.880 回答