动态添加控件 C#
dinamcally adding controls C#
我正在尝试在应用程序初始化时创建一个新标签。我已经 运行 浏览了其他问题和答案并做出了这样的事情:
public Form1()
{
InitializeComponent();
try
{
foreach (Button b in Controls)
{
FillBoard(b);
}
Label tScore = new Label();
tScore.Size = new Size(244, 22);
tScore.Location = new Point(12, 46);
tScore.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
tScore.Text = "Some text";
tScore.Visible = true;
Controls.Add(tScore);
Show();
Refresh();
}
catch { }
}
但是当我启动应用程序时标签仍然没有出现。我做错了什么?
您的应用程序在 foreach (Button b in Controls)
崩溃。
您正在尝试将所有控件转换为不起作用的按钮。
你应该像这样迭代它。
foreach (Control b in Controls)
{
if (b is Button)
{
FillBoard(b);
}
}
只有一个错误。 this.Controls.Add(标签);
我正在尝试在应用程序初始化时创建一个新标签。我已经 运行 浏览了其他问题和答案并做出了这样的事情:
public Form1()
{
InitializeComponent();
try
{
foreach (Button b in Controls)
{
FillBoard(b);
}
Label tScore = new Label();
tScore.Size = new Size(244, 22);
tScore.Location = new Point(12, 46);
tScore.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
tScore.Text = "Some text";
tScore.Visible = true;
Controls.Add(tScore);
Show();
Refresh();
}
catch { }
}
但是当我启动应用程序时标签仍然没有出现。我做错了什么?
您的应用程序在 foreach (Button b in Controls)
崩溃。
您正在尝试将所有控件转换为不起作用的按钮。
你应该像这样迭代它。
foreach (Control b in Controls)
{
if (b is Button)
{
FillBoard(b);
}
}
只有一个错误。 this.Controls.Add(标签);