简体   繁体   English

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

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

I have problem like below,我有如下问题,

I need to create UserControl that is placed in different forms.我需要创建放置在不同 forms 中的UserControl But it's behaviour depends of the form it is placed in.但它的行为取决于它所处的形式。

Example: Form1 has button that takes data from db and sends it to my UserControl .Then it creates let's say another control that can be clicked but when clicked it calls db (depends on Form1 ) and crates new controls below.示例: Form1具有从 db 获取数据并将其发送到我的UserControl的按钮。然后它创建假设另一个可以单击但单击时调用 db 的控件(取决于Form1 )并在下面创建新控件。

Form2 does the same but different db calls. Form2执行相同但不同的数据库调用。

Problem form me is how calls the second call from UserControl - how make query to db when it depends on from external form used?我的问题是如何从UserControl调用第二个调用 - 当它依赖于使用的外部表单时如何对 db 进行查询?

That sounds like an ABSOLUTELY HORRIBLE design, but this is how you'd do it:这听起来像是一个绝对可怕的设计,但这就是你的做法:

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