简体   繁体   中英

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. 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.

Form2 does the same but different db calls.

Problem form me is how calls the second call from UserControl - how make query to db when it depends on from external form used?

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

        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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