2017-09-21 226 views
0

我是C#的初学者。我在一个类中定义了DataGridvew“dgPins”以及名为“pnlPins”的Panel。该应用程序使用几个UI组合在一起设计。初始化是在类X如下从另一个类访问同一个类的DataGridView实例

private void InitializeComponent() { 
    ... 
    private System.Windows.Forms.Panel pnlPINs; 
    private System.Windows.Forms.DataGridView dgPins; 
    ... 
} 

我使用此网格显示一些销从连接到以太网设备读出的完成。一旦数据被填满它看起来像这样(这是一个按钮,点击一下鼠标),

private void mnuGeraetLesen_Click(object sender, EventArgs e) 
{ 
    ... 
    if (EthernetAvailable == true) 
    { 
     QueryAllCodeCommandHandler();// local function which fills the grid 
    } 
} 

enter image description here

现在在另一个UI(类)我有一个按钮,需要访问同一网格 实例并执行相同的任务。所以我在这个班上做了以下的事情(比如说Y班)。

private void _btnSearchDevices_Click(object sender, EventArgs e) 
{ 
    SingleDeviceInformationControl test = new SingleDeviceInformationControl(); 
    test.QueryAllCodeCommandHandler(); 
} 

但据我所知,这将创建一个不同的实例,将无法正常工作。所以网格保持如下空。

enter image description here

我想重命名DataGridView的公共静态这使我能够从任何地方访问同一个实例,但它使整个项目的不稳定。 我已经做了一些研究,发现了类似的问题,但还没有理解我真的必须做些什么才能达到预期的结果。我非常感谢有关此问题的可能解决方案的任何提示。非常感谢你!

+0

既然你声明你的DataGridView是私有的,你只能从同一个类访问它,而不能从其他地方访问它。因此,无论您需要将其声明为public,还是需要编写setter和getter方法来访问DataGridView(请参阅[公共,私有,受保护和没有任何区别](https://stackoverflow.com/questions/614818)/what-is-the-difference-between-public-private-protected-and-nothing)以供参考)。通过将网格视图声明为公共,我也不明白你的项目变得不稳定了吗? – waka

+0

对不起,我的坏。它不会改变任何东西。因为我忘了提及(坏)那些是单独的用户界面 – Isuru

回答

0

如果您以其他形式实例化YourForm,则必须让您的Grid Public访问它或将私有网格封装在“公共”属性中。

如果您在谈论单独的UI或UserContorls您可以创建一个用户界面的静态实例,就像这样,您有义务将您的网格从私有修改为公共。但是,建议您封装专用网的“公共”属性

private static YourForm _instance; 

/// <summary> 
/// static Instance of YourForm 
/// </summary> 
public static YourForm Instance 
{ 
    get 
    { 
    if (_instance == null) 
     _instance = new YourForm(); 
    return _instance; 
    } 
} 

YourForm是包含网格的形式,然后你可以访问到您的网这样

YourForm.Instance.dgPins

这方法通常与UserControls一起使用

+0

是的,它与UserControls。我尝试过,但网格仍然是空的 – Isuru

相关问题