DannyDSB Official
DannyDSB Official

Reputation: 17

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.

Upvotes: 0

Views: 122

Answers (3)

Idle_Mind
Idle_Mind

Reputation: 39122

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);
}

Upvotes: 0

alobster
alobster

Reputation: 38

Create panel:

var panel = new Panel();
this.Controls.Add(panel);

Create button:

var button = new Button();
this.Controls.Add(button);

Add event handler to button:

button.Click += (o,e) =>
{
  panel.Visible = !panel.Visible;
};

Upvotes: 1

CShark
CShark

Reputation: 1563

First you need the name of the panel. You need to set its visibility property to change the visibility (duh.)

To do that on a button click, you need to attach an event handler to it. Let's first assume that you called your newly created button "myButton" for simplicities sake.

First you create the handler function

void myButton_Click(object sender, RoutedEventArgs e){
    panel.visibility = whatever;
}

and later assign the function to the click handler with

myButton.Click += myButton_Click;

Upvotes: 0

Related Questions