I have 10 panels all visible = false and have 10 buttons
I wanna when click on button(b1)
The new location and new size for all panels are same, Can I make a function do the relocate and resize instead of write a code more times like this
private void b1_Click(object sender, EventArgs e)
{
p1.Visible = true;
p1.Location = new System.Drawing.Point(9, 247);
p1.Size = new System.Drawing.Size(1120, 464);
}
You can assign all buttons' click event to the same event handler. The parameter sender is the object that fires the event which in your case it is one of your buttons. Then check the sender's Text or Name property and find which button was clicked. For panels, you could make a method with a Panel type parameter and do what you want.
private void btn_Click(object sender, EventArgs e)
{
// here put code to hide all panels
//...
//then show and relocate the panel related the clicked button as follows
switch ((sender as Button).Name) //or button's Text
{
case "b1":
showPanel(pl);
break;
case"b2":
showPanel(p2);
break;
//other cases
//...
}
}
private void showPanel(Panel pnl)
{
//show and relocate
pnl.Visible = true; //I consider pnl.Show(); as it's more readable
//...
}
Don't forget to hide all panels at the beginning of the click event. You can use following method if you do not have any other panel in your control except those 10 ones.
private void hidePanels()
{
foreach (Control c in yourControl.Controls) //replace yourControl with the control that is the container of your panels e.g. your form
{
if (c is Panel) c.Visible = false; //or c.Hide();
}
}
I haven't tested this code, but it should work.