Home > other >  PictureBox Group - How To Align As Grid?
PictureBox Group - How To Align As Grid?

Time:10-07

I have some picture boxes that are added as they are iterated.

Urls are fetched from a database table and looped while adding the PictureBox control with X/Y coordinates.

I figured out after trial and error how to get them aligned in a horizontal row, but issues arise when I want to break the row after 11 pictures, and continue below (Y: first image height 5 (padding).

I came up with this formula:

int rowLimit = 11;
Location = new Point(i > 1 ? 27 * i : 0, i > rowLimit ? i * 27 : 0)

Which got me this

enter image description here

Great. Nearly there.. until I attempt to work at next row below.

How can I get this as 11 across, and however many left as rows below?

int i = 0;
int rowLimit = 11;
foreach (DataRow row in dt.Rows)
{
   i  ;
   var picture = new PictureBox
   {
      Name = "pictureBox",
      Size = new Size(25, 25),
      Location = new Point(i > 1 ? 27 * i : 0, i > rowLimit ? i * 27 : 0),
      ImageLocation = "https://example.com/"   row["avatar"].ToString()
   };
   Controls.Add(picture);
}

If I need to use a flexpanel, please advise.

Any help very appreciated :)

NOTE: Ignore the broken images, it is expected as some avatars are in fact broken (we deal with this later).

CodePudding user response:

You could leverage another part of winforms, like a table or grid array, but assuming you want to stick with this tool...

Looks like the current Y coordinate of the location will just stack everyting greater than rowLimit vertically. You might consider utilizing integer division to your advantage, like this:

Location = new Point(i > 0 ? i * (Size.X   2) : 0, i / rowLimit > 0 ? i * (Size.Y   2) : 0)

Here, i / rowLimit will be 0 when i is between 0 and 10, then 1 when i is between 11 and 21, etc.

  • Related