从Windows窗体控件中按名称查找控件

时间:2022-01-21 15:50:15

I have a list of my textbox names, and I want to find a control by name. How is it possible?

我有一个文本框名称列表,我希望按名称查找控件。这怎么可能?

3 个解决方案

#1


81  

Use Control.ControlCollection.Find.

使用Control.ControlCollection.Find。

TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";

EDIT for asker:

为提问者编辑:

Control[] tbxs = this.Controls.Find(txtbox_and_message[0,0], true);
if (tbxs != null && tbxs.Length > 0)
{
    tbxs[0].Text = "Found!";
}

#2


9  

You can use:

您可以使用:

f.Controls[name];

Where f is your form variable. That gives you the control with name name.

其中f是表单变量。这为您提供了名称控件。

#3


3  

TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";

If Controls.Find is not found "textBox1" => error. You must add code.

如果未找到Controls.Find,则“textBox1”=>错误。您必须添加代码。

If(tbx != null)

Edit:

编辑:

TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
If(tbx != null)
   tbx.Text = "found!";

#1


81  

Use Control.ControlCollection.Find.

使用Control.ControlCollection.Find。

TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";

EDIT for asker:

为提问者编辑:

Control[] tbxs = this.Controls.Find(txtbox_and_message[0,0], true);
if (tbxs != null && tbxs.Length > 0)
{
    tbxs[0].Text = "Found!";
}

#2


9  

You can use:

您可以使用:

f.Controls[name];

Where f is your form variable. That gives you the control with name name.

其中f是表单变量。这为您提供了名称控件。

#3


3  

TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";

If Controls.Find is not found "textBox1" => error. You must add code.

如果未找到Controls.Find,则“textBox1”=>错误。您必须添加代码。

If(tbx != null)

Edit:

编辑:

TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
If(tbx != null)
   tbx.Text = "found!";