我正在使用以下代码手动将datagrid视图添加到我的表单但问题是当我想添加datagridview click事件时它会出错
Dim DgvUs(10) As DataGridView
Public Sub Add(ByVal dgNum As Integer)
DgvUs(dgNum) = New DataGridView
Dim cl1 As New DataGridViewTextBoxColumn
cl1.HeaderText = "cA"
cl1.Name = "cA"
cl1.Width = 90
Dim cl2 As New DataGridViewTextBoxColumn
cl2.HeaderText = "cB"
cl2.Name = "cB"
cl2.Width = 90
DgvUs(dgNum).Columns.Add(cl1)
DgvUs(dgNum).Columns.Add(cl2)
DgvUs(dgNum).RowHeadersVisible = False
DgvUs(dgNum).Width = 180
DgvUs(dgNum).ScrollBars = ScrollBars.Vertical
DgvUs(dgNum).Dock = DockStyle.Left
DgvUs(dgNum).Columns(0).SortMode = DataGridViewColumnSortMode.NotSortable
DgvUs(dgNum).Columns(1).SortMode = DataGridViewColumnSortMode.NotSortable
DgvUs(dgNum).AllowUserToAddRows = False
panelN.Controls.Add(DgvUs(dgNum))
End Sub
添加datagridview工作正常但是 单击“事件给出错误”
Private Sub DGV_MouseClick(ByVal sender As Object, ByVal e As MouseEventArgs) _
Handles DgvUs(1).MouseClick
'Click Event
End Sub
('。'预期)
任何建议/解决方案
答案 0 :(得分:2)
这不是您在运行时添加事件的方式(这是您在设计时添加事件的方式)。你必须在这些行上使用代码:
AddHandler DgvUs(dgNum).MouseClick, AddressOf DGV_MouseClick
将方法转换为:
Private Sub DGV_MouseClick(ByVal sender As Object, ByVal e As MouseEventArgs)
Dim curDGV As DataGridView = DirectCast(sender, DataGridView) 'This is the DataGridView you are currently clicking on
End Sub