I am trying to add a PictureBox dynamically to a TableLayoutPanel but it's not filling the selected cell

I use this part of code to add the picture but it's half the cell...and still it's not working.

PictureBox pB = new PictureBox {
  Size = MaximumSize,
  Dock = DockStyle.Fill,
  BackgroundImageLayout = ImageLayout.Stretch
};

OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK) {
  string path = ofd.FileName;
  pB.Image = new Bitmap(path);
}

tableLayoutPanel1.Controls.Add(pB, x-1, y-1);
Control control = tableLayoutPanel1.GetControlFromPosition(x - 1, y - 1);
control.Dock = DockStyle.Fill;
control.BackgroundImageLayout = ImageLayout.Stretch;

Upvotes: 0

Views: 1400

Answers (1)

TaW
TaW

Reputation: 54453

You are confusing the two images a PictureBox can have:

  • The Image is the main one with all sorts of capabilties
  • The BackgroundImage is below it and can be use for just that: A background.

You want to set the layout for the Image; it is called SizeMode

PictureBox pB = new PictureBox
{
    Size = MaximumSize,
    Dock = DockStyle.Fill,
    SizeMode = PictureBoxSizeMode.StretchImage
};

Not sure where and how you set x and y but you should see the full image now, albeit more or less stretched.

And you don't need to set the SizeMode or Docking again at the end..

Upvotes: 1

Related Questions