按给定名称编辑按钮
本文关键字:编辑按 按钮 编辑 定名称 | 更新日期: 2023-09-27 17:52:50
我正在生成x个按钮,并为所有按钮指定一个唯一的名称。
生成所有这些之后,我想编辑其中一个,而不重新生成它们,所以我想知道是否可以按名称获取组件?
我正在使用WinForms
是:
Control myControl = Controls.Find("textBox1");
现在,请注意,您必须对找到的母鸡进行正确的铸造,因为Find返回一个控件。
您可以使用表单的Controls
属性(或表单上的一些容器控件(。使用LINQ,您可以选择按钮,然后找到第一个具有所需名称的按钮:
var button1 = Controls.OfType<Button>().FirstOrDefault(b => b.Name == "button1");
或者,如果你想递归地搜索子控件
var button1 = Controls.Find("button1", true)
.OfType<Button>()
.FirstOrDefault();
如果没有LINQ,您可以使用ControlCollection:的方法Find(字符串键,boolsearchAllChildren(
Control[] controls = Controls.Find("button1", true);
if (controls.Length > 0)
{
Button button1 = controls[0] as Button;
}
Button btn1 = (Button)(Controls.Find("btnName"));
这将获得所需的按钮,并将按钮属性保存到新的按钮btn1
生成所有这些之后,我想编辑其中一个再生它们,所以我想知道是否可以通过名称
var myButton = Controls.Find("buttonName", true).FirstOrDefault(); //Gets control by name
if(myButton != null)
{
if (myButton.GetType() == typeof(Button)) //Check if selected control is of type Button
{
//Edit button here...
}
else
{
//Control isn't a button
}
}
else
{
//Control not found.
}
请确保添加对:linq的引用。