首页 > 解决方案 > C# UserControl 取决于它所在的表单 - WinForms

问题描述

我有如下问题,

我需要创建UserControl以不同形式放置的。但它的行为取决于它所处的形式。

示例: Form1具有从 db 获取数据并将其发送到我的按钮UserControl。然后它创建假设另一个可以单击的控件,但是单击时它会调用 db(取决于Form1)并在下面创建新控件。

Form2执行相同但不同的数据库调用。

我的问题是如何调用第二个调用UserControl- 当它依赖于使用的外部表单时如何对数据库进行查询?

标签: c#selenium-webdriverc#-4.0user-controls

解决方案


这听起来像是一个绝对可怕的设计,但这就是你的做法:

private void button1_Click(object sender, EventArgs e)
{
    if (this.ParentForm != null)
    {
        if (this.ParentForm is Form1)
        {
            Form1 f1 = (Form1)this.ParentForm; // if you need a reference to the Form1 instance
            // ... do stuff for Form1 ...
        }
        else if (this.ParentForm is Form2)
        {
            Form2 f2 = (Form2)this.ParentForm; // if you need a reference to the Form2 instance
            // ... do stuff for Form2 ...
        }
        else if (...)
        {

        }
    }
}

推荐阅读