Search code examples
c#winformsscrollbarpanelvertical-scrolling

Adding a vertical scrollbar and "line break" on a Panel depending on its items' sizes


I would like to display the result of each line of a SqlDataReader object in the form of several dynamic groupBoxes, adeed to an existing panel.

I also want an automatic line break when one of these groupboxes provokes an horizontal overflow in the containing panel, instead of keeping being added one after another from left to right.

So when a groupbox is out of the horizontal bounds of the panel, it gets placed on a new "line" instead, under the previous groupboxes.

Here is my code:

SqlCommand cmd = new SqlCommand(sqlString, cnx); //return;
SqlDataReader myReader;
myReader = cmd.ExecuteReader(); 
int i = 0; int j = 0;
int sw = Screen.PrimaryScreen.Bounds.Width;//sw=1920
int sh = Screen.PrimaryScreen.Bounds.Height;//sh=1080

panel1.HorizontalScroll.Maximum = 0;
panel1.AutoScroll = false;
panel1.VerticalScroll.Visible = false;
panel1.AutoScroll = true;

while (myReader.Read())
{
    MessageBox.Show("Results : \n Distinct values : " + myReader["column1"].ToString() + " Occurence number  : " + myReader["nbre_column1"].ToString());                        
    //I can show all values including on myReader on this message box

    GroupBox resultGroupBox = new GroupBox();
    resultGroupBox.Size = new System.Drawing.Size((sw * 20) / 100, (sh * 20) / 100);
    resultGroupBox.Location = new Point(44 + i, 36);
    i = i + 390;
    //j = j + 220;
    panel1.Controls.Add(resultGroupBox);
}

in summary I would like to have two things:

  1. A "line break" for dynamically added groupboxes, once their combined width exceeds the width of the panel, and no horizontal scrollbar
  2. A vertical scrollbar when the combined height of all the "lines" of groupboxes exceeds the panel's height.

The code provided doesn't prevent the horizontal scrollbar from appearing, and if the j = j + 220 line is uncommented, both scrollbars appear, but no line break.

Thanks in advance for your help.


Solution

  • Use a FlowLayoutPanel instead of a Panel, and set its properties this way (if they're not already):

    • Autoscroll: True; adds a vertical scrollbar when needed
    • WrapsContent: True; allows the content to wraps horizontally when needed