0

I would like my every new button that is created dynamically to be on top of the old button at a particular location. What should I do ? Bring To Front doesn't help me in getting to it. Below is my Code

    int l=0;
    public void CreateButton_Click(object sender, EventArgs e)
    {
        Button exitButton1 = new Button();
        l++;
        exitButton1.Text = "X("+l+")";
        exitButton1.Top = 500;
        exitButton1.Left = 10;
        exitButton1.Width = 50;
        exitButton1.Height = 30;

        exitButton1.Click += (_, args) =>
        {
            exitButton1.Hide();
        };

        this.Controls.Add(exitButton1);
    }
Animesh
  • 19
  • 5
  • I don't know; but doing this in general is really, really weird. There should only be one button – BradleyDotNET Jan 18 '18 at 16:50
  • Possible duplicate of [How to set Z-order of a Control using WinForms](https://stackoverflow.com/questions/3213270/how-to-set-z-order-of-a-control-using-winforms) – PaulF Jan 18 '18 at 16:52
  • Where were you calling `.BringToFront()`? When I add `exitButton1.BringToFront();` after the code you showed it works fine. – Equalsk Jan 18 '18 at 16:52
  • I added it just below exitButton1 . Height – Animesh Jan 18 '18 at 16:55
  • Put it as the last line of this code underneath `this.Controls.Add(exitButton1);` – Equalsk Jan 18 '18 at 16:58
  • Thank you Sir, it really helped me. – Animesh Jan 18 '18 at 17:03
  • If all buttons appear at the same location, and hence only one can be visible at any given point in time, why don't you just use the same button all the time, and just change the `.Text` property of it? – Heinz Kessler Jan 18 '18 at 18:56
  • Well that's really a very good idea Sir, I really like that. As because I am new to C#, I thought of using this as as Undo Button(so I wanted all my buttons on the same location), so that it would be easier for me to undo all my tasks one by one. – Animesh Jan 18 '18 at 19:19

1 Answers1

0

Simply with List<button> you can do it:

    int l=0;
    List<Button> buttons = new List<Button>();
    private void button1_Click(object sender, EventArgs e)
    {
        Button exitButton1 = new Button();
        l++;
        exitButton1.Text = "X(" + l + ")";
        exitButton1.Top = 10;
        exitButton1.Left = 10;
        exitButton1.Width = 50;
        exitButton1.Height = 30;

        exitButton1.Click += (_, args) =>
        {
            exitButton1.Hide();
            buttons.Remove(exitButton1);

            if (buttons.Count() != 0)
            {
                buttons[buttons.Count - 1].Show();
            }
        };

        if (buttons.Count() != 0)
        {
            buttons[buttons.Count - 1].Hide();
        }

        buttons.Add(exitButton1);
        this.Controls.Add(exitButton1);
    }
Mazaher Bazari
  • 421
  • 5
  • 12