Technical
Technical

Reputation: 154

C# - Reordering controls by z-index in Panel

I have a Panel with a PictureBox with Dock = DockStyle.Fill. I need to dynamically add controls to the Panel, but they must stay above the PictureBox.

This is easy within the Designer, but when I do this programmatically, neither SetChildIndex(), BringToFront() or SendToBack() work.

I have to use PictureBox, I can't just set Panel.BackgroundImage because it's glitchy.

Upvotes: 0

Views: 754

Answers (2)

L_J
L_J

Reputation: 2437

Once you add your dynamic control to the Controls find it and BringToFront like as follows:

TextBox tb = new TextBox
{
    Location = new Point(100, 100),
    Name = "Textbox1"
};

this.Controls.Add(tb);

var contr = Controls.Find("Textbox1", true)[0];
contr.BringToFront();

Alternatively, once you add new dynamic control. Apply SendToBack to the PictureBox.

  pictureBox1.SendToBack();

lion

Upvotes: 1

Any Moose
Any Moose

Reputation: 648

I fount this to be an issue with the order of the controls in the panel in the design.cs

Remove the controls from the panel and add them in the correct order.

        this.panel1.Controls.Add(this.pictureBox1);
        this.panel1.Controls.Add(this.button1);
        this.panel1.Location = new System.Drawing.Point(12, 12);
        this.panel1.Name = "panel1";
        this.panel1.Size = new System.Drawing.Size(260, 238);
        this.panel1.TabIndex = 0;

button under piturebox

        this.panel1.Controls.Add(this.button1);
        this.panel1.Controls.Add(this.pictureBox1);
        this.panel1.Location = new System.Drawing.Point(12, 12);
        this.panel1.Name = "panel1";
        this.panel1.Size = new System.Drawing.Size(260, 238);
        this.panel1.TabIndex = 0;

enter image description here

Upvotes: 2

Related Questions