How to get same effect from docking controls inside panel in code, as if docking them from designer?

StackOverflow https://stackoverflow.com/questions/17530301

  •  02-06-2022
  •  | 
  •  

Pergunta

enter image description here

The problem, as you see on picture. If I fill panel in code like this:

private void Form1_Load(object sender, EventArgs e)
{
    Panel pnl = new Panel();
    PictureBox pb = new PictureBox();
    TextBox txt = new TextBox();

    pnl.BorderStyle = BorderStyle.FixedSingle;
    pb.BorderStyle = BorderStyle.FixedSingle;
    pb.Dock = DockStyle.Top;
    txt.Dock = DockStyle.Fill;

    pnl.Controls.Add(pb);
    pnl.Controls.Add(txt);
    this.Controls.Add(pnl);
}

The TextBox still goes to 0,0 position inside panel

Foi útil?

Solução

You have to add the control with DockStyle.Fill first.

This can also be done in code by using the Controls.SetChildIndex method and setting the ChildIndex of the control using DockStyle.Fill to alower number as the others.

In the Document Outline view of Visual Studio you can sort the controls up and down which sets the ChildIndex in the x.Designer.cs file.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top