在表格中找到用户控件 [英] find usercontrol in form

查看:71
本文介绍了在表格中找到用户控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的所有人,

我创建了一个名为Basecontrol的用户控件,然后将一些基本控件添加到窗体中.然后尝试查找所有用户控件:

Dear all,

I created a usercontrol called Basecontrol and then add some basecontrols into form. Then try to find all the usercontrols:

foreach (BaseControl c in this.Controls)
{
  if (c.Name == "test1")
  {
    ///////My code;         
  }


但是它失败了.请帮帮我!

在此先感谢您.


However it fails. Please help me!

Thanks in advance.

推荐答案

您应该这样操作:
You should do it this way:
foreach (Control c in this.Controls)
{
    if(c is BaseControl)
    {
        if (c.Name == "test1")
        {
            ///////My code;
        }
    }
}


如果表单上只有BaseControl,则此代码没有错.如果还有其他控件(例如TextBox),它将引发错误无法将TextBox转换为BaseControl".

请尝试:
This code is not wrong if there are only BaseControl on the form. If there is other control such as TextBox, it will raise error "Cannot convert TextBox to BaseControl".

Please try:
foreach (Control c in this.Controls)
{
if (c.Name == "test1")
{
  //Your code;
}


每个忘记了控件的人都应该递归搜索:

按名称:

Everyone forgot a control should be searched recursively:

By name:

Control FindControl(Control control, string name) {
    if (control.Name == name)
        return control;
    foreach(Control child in control.Controls) {
        Control found = FindControl(control, name);
        if (found != null)
            return found;
    } //loop
    return null; //SA!!! important!
} //FindControl



谓词非常糟糕:为什么要命名呢? (仅是因为在问题中就是这样.)而且,没有人会保证名称在任何范围内都是唯一的.
也许最好按类型搜索.

最简单的方法是通用的.方法如下:



The predicate is pretty bad: why by name? (Only because it was so in the Question.) Also, nobody will guarantee the name is unique in any scope.
Maybe, it''s better to search by type.

The easiest way is generic. Here is how:

CONTROL_TYPE FindControl<CONTROL_TYPE>(Control control)
            where CONTROL_TYPE : Control {
    if (control is CONTROL_TYPE)
        return (CONTROL_TYPE)control; //save due to the check above
    foreach (Control child in control.Controls) {
        CONTROL_TYPE found =
            FindControl<CONTROL_TYPE>(control);
        if (found != null)
            return found;
    } //loop
    return null; //SA!!! important!
} //FindControl



通常,整个设计依赖于控件的搜索是很糟糕的.
在极少数情况下,它可能很有用.无论如何,它回答了这个问题.

祝你好运!



Generally whole design relying on search of control is pretty bad.
In some rare cases it can be useful. Anyway, it answers the question.

Good luck!


这篇关于在表格中找到用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆