繁体   English   中英

C# UserControl 取决于它所在的表单 - WinForms

[英]C# UserControl depends of form it is place in - WinForms

我有如下问题,

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

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

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

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

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

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 (...)
        {

        }
    }
}

暂无
暂无

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

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