在c#中连接控件名称

本文关键字:控件 连接 | 更新日期: 2023-09-27 18:11:53

我不知道该怎么说,我有3个datagridview控件(命名为datagridview1, datagridview2 &datagridview3)。我的问题是我能把这些控件的名字连接起来吗?

我的意思是我可以这样称呼它吗:datagridview(n) or datagridview + n

我用的是winforms。

提前感谢!

在c#中连接控件名称

我认为你想要的是找到一个动态名称的控件?

可能是这样的:

Control match = ParentControl.Controls["datagridview" + n];
例如,如果你所有的数据网格都在一个名为"MyPanel"的面板中,那么你可以这样做:
DataGridView match = MyPanel.Controls["datagridview" + n] as DataGridView;

但是,如果您的数据网格并不都属于同一个父控件,那么您可以使用控件找到它们。寻找方法:

DataGridView match = this.Controls.Find("datagridview" + n, true)[0] as DataGridView;

注意:控件。Find方法返回一个数组,因此您需要选择第一个元素(假设您的控件名称是唯一的),在尝试访问第一个元素之前检查数组是否有任何值也可能是值得的。


如果你想把它包装在一个函数中,你可以这样做:

public DataGridView GetDataGridViewForTabNumber(int n){
    Control[] matches = this.Controls.Find("datagridview" + n, true);
    if(matches.length == 0) 
        return null;
    return matches[0] as DataGridView;
}

并这样命名:

DataGridView dgv = GetDataGridViewForTabNumber(1);//gets datagridview1

注意:如果你在运行时动态创建DataGridView控件,这是一个完全有效的方法。然而,如果你是在设计器中创建它们,那么,就像Tim说的,你应该给它们一个更有意义的名字,并直接引用它们。

Try This

DataGridView dg = (DataGridView)this.Controls.Find(" DataGridView "+n.ToString(), true);