简体   繁体   中英

How can I make a function to relocate and resize a set of controls

I have 10 panels all visible = false and have 10 buttons

  1. panels name = p1, p2, p3...etc
  2. buttons name = b1, b2, b3...etc

I wanna when click on button(b1)

  1. make panel(p1) visible = true
  2. relocate and resize panels

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.

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