0

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.

Technical
  • 145
  • 1
  • 11

2 Answers2

2

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

Any Moose
  • 723
  • 6
  • 12
  • This is exactly what I needed. Kinda doesn't makes sense at first because pictureBox1 is added later, but stays "beneath" button1. – Technical Aug 02 '18 at 16:41
1

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

L_J
  • 2,351
  • 10
  • 23
  • 28