C#在循环中添加控制面板 [英] C# Add Controls To Panel In a Loop
本文介绍了C#在循环中添加控制面板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望为文件中的每行添加一个按钮。
我的代码是:
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.
推荐答案
代码看起来不错,但可能有以下情况。
The code looks fine but there could be a following situations.
1.您可能只有一个条目在文件中,所以您只会在面板中添加一个按钮。
1.You might have only one entry in the file, so you are experiencing only One Button added to the panel.
2.您的面板宽度小于所有动态按钮宽度的总和
我怀疑没有2是导致问题的主要原因。
I suspect no 2 is the main reason that is causing problem.
所以,我建议您使用 FlowLayoutPanel 。添加动态内容,因为它会自动布局所有子控件。
So, I recommend that you use FlowLayoutPanel. To add a dynamic content as it automatically layout all the child controls.
这篇关于C#在循环中添加控制面板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文