我在现有的WinForm项目上使用C#.原始代码使用Tag来传递一组文本框的硬件寻址信息,这些文本框代表连接的微控制器系统中的某些硬件寄存器.我知道如何通过使用Control.ControlCollection.Find方法搜索其名称来查找未知控件,但我不清楚是否可以通过Tag找到控件(在此实例中只是一个字符串).
sab*_*669 11
跟进我的评论:
private void FindTag(Control.ControlCollection controls)
{
foreach (Control c in controls)
{
if (c.Tag != null)
//logic
if (c.HasChildren)
FindTag(c.Controls); //Recursively check all children controls as well; ie groupboxes or tabpages
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以在if语句中获取控件名称,并从那里执行您想要执行的操作.
只需在此解决方案中添加一个编辑,因为几年后它仍然会获得不常见的Upvote.您还可以修改此解决方案以检查控制的类型,c并执行不同类型的逻辑.因此,如果您想循环所有控件并处理Textbox单向和RadioButon另一种方式,您也可以这样做.我必须在一些项目上做到这一点,我只能稍微更改上面的代码以使其工作.不一定与OP的问题有关,但我想加上它.
您可以使用LINQ基于的查找控件Tag
var items = parentControl.ControlCollection;
var item = items.Cast<Control>().FirstOrDefault(control => String.Equals(control.Tag, tagName));
Run Code Online (Sandbox Code Playgroud)
public static Control FindByTag(Control root, string tag)
{
if (root == null)
{
return null;
}
if (root.Tag is string && (string)root.Tag == tag)
{
return root;
}
return (from Control control in root.Controls
select FindByTag(control, tag)).FirstOrDefault(c => c != null);
}
Run Code Online (Sandbox Code Playgroud)
将最外面的控件传递给它(即您要搜索的表单或容器).请注意,这包括搜索的根控制.
| 归档时间: |
|
| 查看次数: |
12419 次 |
| 最近记录: |