Vb.net 获取表单中存在的datagridview的名称
如何检查表单上的Vb.net 获取表单中存在的datagridview的名称,vb.net,datagridview,Vb.net,Datagridview,如何检查表单上的datagridview数量,然后在VB.NET中显示并显示它们的名称 我试过这个: For Each dgv As DataGridView In Me.Controls MsgBox(dgv.Name) Next 但我的猜测是,Me.Controls由除DataGridView之外的所有其他表单控件组成。我知道这个问题很久以前就发布了。在@AadityaDengle发布的答案中,您将获得放置在表单中的DataGridView控件,但是如果DataGridVi
datagridview
数量,然后在VB.NET
中显示并显示它们的名称
我试过这个:
For Each dgv As DataGridView In Me.Controls
MsgBox(dgv.Name)
Next
但我的猜测是,
Me.Controls
由除DataGridView
之外的所有其他表单控件组成。我知道这个问题很久以前就发布了。在@AadityaDengle发布的答案中,您将获得放置在表单中的DataGridView
控件,但是如果DataGridView
嵌套在其他控件中(例如Panel
,TableLayoutPanel
,GroupBox
,…),它将找不到它
For Each _control In Me.Controls
If TypeOf _control Is DataGridView Then
MsgBox(_control.Name)
End If
Next
您必须使用“递归搜索”方式在所有控件中进行搜索。下面是一个例子:
'there will be stored names(id) of all DataGridView controls
Private allGrids As String = ""
Private Sub getAllGrids()
'loop through all controls on a form
For Each c As Control In Me.Controls
If TypeOf c Is DataGridView Then
'if control is DataGridView, then collect her name(id)
allGrids += c.Name.ToString + ","
Else
'if control isn't type of DataGridView and have child control(s), loop through that control
'(for example Panel, TableLayoutPanel,GroupBox, ...)
If c.HasChildren = True Then getAllGrids(c)
End If
Next
End Sub
Private Sub getAllGrids(cnt As Control)
'loop through all controls on a "container" control
'the search principle is the same like in getAllGrids on a form
For Each c As Control In cnt.Controls
If TypeOf c Is DataGridView Then
'collect DataGridView name(id)
allGrids += c.Name.ToString + ","
Else
'subroutine call hisself again with new control
If c.HasChildren = True Then getAllGrids(c)
End If
Next
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MsgBox(allGrids)
End Sub
尽管@AadityaDengle和@nelek的两个答案都是正确的,但我将把我的代码留在这里,因为我认为它更有条理 请注意,此代码在
数据网格视图
放置在面板
或组框
中时,无论是否使用,都可以使用
如果您的datagridview
嵌套在Panel
或类似的东西中,则需要通过如下参数发送指定的Panel
-
FormDGV(YourPanel)
但如果不是,你只需要把表格寄过来就行了
FormDGV(YourPanel)