如何获取在运行时创建的控件的文本?
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
}
答案 0 :(得分:2)
var b = this.Controls.OfType<Button>().FirstOrDefault(b => b.Name == "mybtn");
if (b == null) { return; }
Console.WriteLine(b.Text);
答案 1 :(得分: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);
}
}
答案 2 :(得分: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);
}
答案 3 :(得分:0)
private void button2_Click(object sender, EventArgs e)
{
Console.WriteLine(this.Controls.Find("myBtn", false).FirstOrDefault().Text);
}