C# Add Controls To Panel In a Loop

YoshieMaster picture YoshieMaster · Jun 20, 2011 · Viewed 79.2k times · Source

I wish to add a button for every line in a file to a panel. My code so far is:

StreamReader menu = new StreamReader("menu.prefs");
int repetition = 0;

while(!menu.EndOfStream)
{
    Button dynamicbutton = new Button();
    dynamicbutton.Click += new System.EventHandler(menuItem_Click);
    dynamicbutton.Text = menu.ReadLine();
    dynamicbutton.Visible = true;
    dynamicbutton.Location = new Point(4+repetition*307, 4);
    dynamicbutton.Height = 44;
    dynamicbutton.Width = 203;
    dynamicbutton.BackColor = Color.FromArgb(40,40,40);
    dynamicbutton.ForeColor = Color.White;
    dynamicbutton.Font = new Font("Lucida Console", 16);
    dynamicbutton.Show();
    menuPanel.Controls.Add(dynamicbutton);
    repetition++;
    MessageBox.Show(dynamicbutton.Location.ToString());
}
menu.Close();

The problem is that only the first control gets created.

Answer

crypted picture crypted · Jun 20, 2011

The code looks fine but there could be a following situations.

1.You might have only one entry in the file, so you are experiencing only One Button added to the panel.

2.Your panel width is smaller than the sum of all the dynamic buttons width.

I suspect no 2 is the main reason that is causing problem.

So, I recommend that you use FlowLayoutPanel. To add a dynamic content as it automatically layout all the child controls.