如何使用 C#.NET 在运行时创建包含按钮文本框标签计时器的面板

本文关键字:标签 文本 计时器 按钮 包含 何使用 NET 创建 运行时 | 更新日期: 2023-09-27 18:31:15

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);
        }
    }
}

我使用它创建了一个面板,但我无法访问在运行时创建的按钮。

如何使用 C#.NET 在运行时创建包含按钮文本框标签计时器的面板

无法访问按钮,我猜你的意思是你没有针对它们的Click事件?

只需要添加它,就像您为Timer所做的那样:

if (c.GetType() == typeof(Button))
{
    c2 = new Button();
    c2.Click += cloneButtonsClick;
}

这将为所有Buttons创建一个通用Click事件。

因此,如果您需要检查 pressed哪个按钮 ,假设有多个。您可以通过其Name(如果已设置)或其Text来执行此操作。(或您设置的任何其他属性,例如Tag)将sender转换为Button后,您可以进行测试并编写点击操作的代码..:

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
     //..
    }

在应用程序中创建面板有很多选项。如果我猜对了,你需要在另一个代码块中获取按钮。所以你可以使用 linq-expression:

var buttons = this.Controls.OfType<Panel>().Where(x => x is Panel).SelectMany(x => x.Controls).OfType<Button>();

或者,您可以将它们存储在局部变量中,以便在创建时快速访问:

if (c.GetType() == typeof(Button))
{
    c2 = new Button();
    buttons.Add(c2);     // where buttons is List<Button>();
}

但我认为最好的选择是创建一个用户控件(panel1 的副本),而不是将动态面板的实例相乘并将一些属性/事件提取到外部。