简体   繁体   English

容器内的VB.Net DataGridView不起作用

[英]VB.Net DataGridView within Container not Working

I have the code below in VB.Net; 我在VB.Net中有以下代码; tested for the 4 cases listed here: 测试了此处列出的4种情况:

1-This code Works; 1-此代码有效; If I make the DataGridView1 variable outside "TabControl1"; 如果我使DataGridView1变量在“ TabControl1”之外;
2-This code NOT Works; 2-此代码无效; If I make the DataGridView1 variable inside "TabControl1"; 如果我在“ TabControl1”中创建DataGridView1变量;
3-This code Works; 3-此代码有效; If I make the DataGridView1 fixed outside "TabControl1"; 如果我将DataGridView1固定在“ TabControl1”之外;
4-This code Works; 4-此代码有效; If I make the DataGridView1 fixed inside "TabControl1"; 如果我将DataGridView1固定在“ TabControl1”内部;

My Question is: How to make it work for case 2 (ie DataGridView1 variable inside "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

As explained in a comment, Me.Controls will only contain controls owned by the form. 如评论中所述, Me.Controls将仅包含该表单拥有的控件。 Controls which are in other container controls ( GroupBox , Panel , TabPage ) will reside in that control's ControlCollection . 其他容器控件( GroupBoxPanelTabPage )中的控件将驻留在控件的ControlCollection

You can use Find to also search those other containers: 您还可以使用“ 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

If you know the name and/or will be referencing it often, it is simpler to declare a variable for it rather than go searching for the same control over and over: 如果您知道名称和/或将经常引用它,那么为它声明一个变量比遍历一遍又一遍地搜索相同的控件更简单:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM