C#- 获取在运行时创建的控件文本

本文关键字:控件 文本 创建 运行时 获取 C#- | 更新日期: 2023-09-27 18:34:43

如何获取在运行时创建的控件的文本?

private void button1_Click(object sender, EventArgs e)
{
    Button btn = new Button();
    btn.Top = 50;
    btn.Left = 50;
    btn.Name = "mybtn";
    btn.Text = "My button";
    this.Controls.Add(btn);
}
private void button2_Click(object sender, EventArgs e)
{
    Console.WriteLine(mybtn.text); // error
}

C#- 获取在运行时创建的控件文本

var b = this.Controls.OfType<Button>().FirstOrDefault(b => b.Name == "mybtn");
if (b == null) { return; }
Console.WriteLine(b.Text);
private void button2_Click(object sender, EventArgs e)
{
    // find mybtn
    Button mybtn = this.Controls.FirstOrDefault(i => i.Name == "mybtn") as Button;
    if (mybtn != null)
    {
        Console.WriteLine(mybtn.Text);
    }
}

将新创建的控件声明为类成员(属性或字段(:

Button btn ;
private void button1_Click(object sender, EventArgs e)
{
    btn = new Button();
    btn.Top = 50;
    btn.Left = 50;
    btn.Name = "mybtn";
    btn.Text = "My button";
    this.Controls.Add(btn);
}

通过表单控件搜索它:

private void button2_Click(object sender, EventArgs e)
{
    Console.WriteLine(this.Controls.Cast<Control>().Single(p=>p.Name == "mybtn").Text);
}
private void button2_Click(object sender, EventArgs e)
{
   Console.WriteLine(this.Controls.Find("myBtn", false).FirstOrDefault().Text);
}