C# 如何使用c.net在运行时创建包含按钮文本框标签计时器的面板
我已经用它创建了一个面板,但是我无法访问在运行时创建的按钮。在应用程序中创建面板有很多选项。如果我没弄错的话,你需要在另一段代码中添加按钮。因此,您可以使用linq表达式:C# 如何使用c.net在运行时创建包含按钮文本框标签计时器的面板,c#,timer,runtime,panel,cloning,C#,Timer,Runtime,Panel,Cloning,我已经用它创建了一个面板,但是我无法访问在运行时创建的按钮。在应用程序中创建面板有很多选项。如果我没弄错的话,你需要在另一段代码中添加按钮。因此,您可以使用linq表达式: private void Add_Timer_Click(object sender, EventArgs e) { number_of_timer++; for (int i = 1; i < number_of_timer; i++) { Panel pnl = new Pa
private void Add_Timer_Click(object sender, EventArgs e)
{
number_of_timer++;
for (int i = 1; i < number_of_timer; i++)
{
Panel pnl = new Panel();
Control c2 = new Control();
pnl.Location = new Point(12, 175*i+25);
pnl.BorderStyle = panel1.BorderStyle;
pnl.BackColor = panel1.BackColor;
pnl.Size = panel1.Size;
pnl.Visible = true;
foreach (Control c in panel1.Controls)
{
if (c.GetType() == typeof(TextBox))
c2 = new TextBox();
if (c.GetType() == typeof(Button))
c2 = new Button();
if (c.GetType() == typeof(Label))
c2 = new Label();
if(c.GetType()== typeof(Timer))
Timer.Tick += new EventHandler(Timer_Tick);
c2.Location = c.Location;
c2.Size = c.Size;
c2.Font = c.Font;
c2.Text = c.Text;
c2.Name = c.Name;
pnl.Controls.Add(c2);
this.Controls.Add(pnl);
}
}
}
或者,您可以将它们存储在局部变量中,以便在创建时快速访问:
var buttons = this.Controls.OfType<Panel>().Where(x => x is Panel).SelectMany(x => x.Controls).OfType<Button>();
但我认为最好的描述是创建panel1的UserControl副本,而不是多个dynamic panel实例,并将一些属性/事件提取到外部。无法访问按钮,我猜您的意思是没有按钮的点击事件
您只需添加它,就像您为计时器所做的那样:
这将为所有按钮创建一个公共单击事件
因此,在事件中,您需要检查按下的按钮,假设有多个按钮。如果您已经设置了它或它的文本,您可以通过它的名称来执行此操作。或您已设置的任何其他属性,如“将发件人强制转换为”按钮后的标记,您可以执行测试并对单击操作进行编码..:
if (c.GetType() == typeof(Button))
{
c2 = new Button();
c2.Click += cloneButtonsClick;
}
这样做毫无意义。改为创建一个UserControl。
if (c.GetType() == typeof(Button))
{
c2 = new Button();
c2.Click += cloneButtonsClick;
}
void cloneButtonsClick(object sender, EventArgs e)
{
Button bt = sender as Button;
if (bt == null) return; // this should never happen!
/* if (bt.Name == "saveButton") { do your things; } // one way to test.. */
if (bt.Text== "Save") { do your things; } // ..another way to test
else if (bt.Text== "Load") { do your things; } // ..another way to test
//..
}