-1

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

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
}
4

4 回答 4

2
var b = this.Controls.OfType<Button>().FirstOrDefault(b => b.Name == "mybtn");
if (b == null) { return; }

Console.WriteLine(b.Text);
于 2013-10-10T16:32:46.610 回答
1
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);
    }
}
于 2013-10-10T16:32:39.847 回答
1

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

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);
}
于 2013-10-10T16:34:24.830 回答
0
private void button2_Click(object sender, EventArgs e)
{
   Console.WriteLine(this.Controls.Find("myBtn", false).FirstOrDefault().Text);
}  
于 2013-10-10T16:46:03.823 回答