DannyDSB Official DannyDSB Official -4 years ago 49
C# Question

C# - Associate panel to button when created programmatically

I wanna make an example application in C# to show to my classmates(I'm 10th grade) how would a Wireless Device Controller Interface work. I know how to write most of the program, but I don't know how to do one thing.

I wanna create a button programmatically and once it is created, associate to it a panel that will show and hide when that button is clicked. Can someone help me?

I forgot to tell you something. The panel needs to be created programmatically too.

Answer Source

Is the Panel also created dynamically? – Idle_Mind

@Idle_Mind yes, it is. I forgot to mention it – DannyDSB Official

The easiest way is to simply store a reference to the Panel in the Tag() property of the Button. Here's a silly example:

private void button1_Click(object sender, EventArgs e)
{
    Panel pnl = new Panel();
    pnl.BorderStyle = BorderStyle.FixedSingle;
    pnl.BackColor = Color.Red;

    Button btn = new Button();
    btn.Text = "Toggle Panel";
    btn.Tag = pnl;
    btn.Click += delegate {
        Panel p = (Panel)btn.Tag;
        p.Visible = !p.Visible;
    };

    flowLayoutPanel1.Controls.Add(btn);
    flowLayoutPanel1.Controls.Add(pnl);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download