VB.Net 容器内的 DataGridView 不工作

VB.Net DataGridView within Container not Working

我在VB.Net中有下面的代码;针对此处列出的 4 个案例进行了测试:

1-此代码有效;如果我在 "TabControl1";
之外创建 DataGridView1 变量 2-此代码无效;如果我在 "TabControl1";
中创建 DataGridView1 变量 3-此代码有效;如果我将 DataGridView1 固定在 "TabControl1";
之外 4-此代码有效;如果我将 DataGridView1 固定在 "TabControl1" 内;

我的问题是:如何使其适用于案例 2(即 "TabControl1" 内的 DataGridView1 变量)?

    Dim CurrentTable As String = "AAAA|BBBBB|CCCCC"
    Dim Values() As String = CurrentTable.Split("|"c)
    Dim DGV As DataGridView ' VARIABLE
    DGV = CType(Me.Controls("DataGridView1"), DataGridView) ' VARIABLE
    DGV.Rows.Add(Split(CurrentTable, "|")) ' VARIABLE
    DataGridView1.Rows.Add(Split(CurrentTable, "|")) ' FIXED

如评论中所述,Me.Controls 将仅包含表单拥有的控件。 other 容器控件(GroupBoxPanelTabPage)中的控件将驻留在 that 中控件的 ControlCollection.

您还可以使用 Find 搜索其他容器:

' TRUE indicates you also want to search child containers
Dim dgvs = Me.Controls.Find("DataGridView1", True)
Dim myDGV As DataGridView
' dgvs will be an array of matching controls, so check
If dgvs.Count > 0 Then
    myDGV = CType(dgvs(0), DataGridView)
End If

如果您知道名称 and/or 将经常引用它,为它声明一个变量比一遍又一遍地搜索相同的控件更简单:

Public Class Form123
   ' form level var:
   Private myDGV As DataGridView

  Private Form_Load(...
     ' set the reference:
     myDGV = DataGridView1