0

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.

3 Answers3

1

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;
};
alobster
  • 38
  • 1
  • 5
0

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;
CShark
  • 1,413
  • 15
  • 25
  • Thank you, but I forgot to mention that the panel needs to be created programmatically like the button. Do you know how to make the association between them? – DannyDSB Official Jun 11 '17 at 08:21
  • It is exactly the same. Just create your panel object (in this case named "panel") and store it in a class-wide available variable. – CShark Jun 11 '17 at 20:07
0

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);
}
Community
  • 1
  • 1
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40