我怎样才能动态地清除用户控件的所有控件? [英] How can I dynamically clear all controls in a user control?

查看:130
本文介绍了我怎样才能动态地清除用户控件的所有控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以动态地(和一般)清除所有的用户控件的子控件的状态? (例如,所有的文本框,DropDrownLists,单选按钮,DataGrid中,中继器等 - 有ViewState的基本上什么)

Is it possible to dynamically (and generically) clear the state of all of a user control's child controls? (e.g., all of its TextBoxes, DropDrownLists, RadioButtons, DataGrids, Repeaters, etc -- basically anything that has ViewState)

我试图避免做这样的事情:

I'm trying to avoid doing something like this:

foreach (Control c in myUserControl.Controls)
{
    if (c is TextBox)
    {
        TextBox tb = (TextBox)c;
        tb.Text = "";
    }
    else if (c is DropDownList)
    {
        DropDownList ddl = (DropDownList)c;
        ddl.SelectedIndex = -1;
    }
    else if (c is DataGrid)
    {
        DataGrid dg = (DataGrid)c;
        dg.Controls.Clear();
    }

    // etc.

}

我在寻找这样的事情:

I'm looking for something like this:

foreach (Control c in myUserControl.Controls)
    c.Clear();

......但显然是不存在的。有没有简单的方法来完成这个动态/一般?

...but obviously that doesn't exist. Is there any easy way to accomplish this dynamically/generically?

推荐答案

我要建议类似任务的,除了一个解决方案(如sixlettervariables指出的),我们需要实现为1扩展方法和essentailly接通$ P在通过控制$ pcise类型(即复制你的逻辑,你张贴在你的问题)。

I was going to suggest a solution similar to Task's except (as sixlettervariables points out) we need to implement it as 1 extension method and essentailly switch on the precise type of the control passed in (i.e. copy your logic that you posted in your question).

public static class ControlExtensions
{
    public static void Clear( this Control c )
    {
        if(c == null) {
            throw new ArgumentNullException("c");
        }
        if (c is TextBox)
        {
            TextBox tb = (TextBox)c;
            tb.Text = "";
        }
        else if (c is DropDownList)
        {
            DropDownList ddl = (DropDownList)c;
            ddl.SelectedIndex = -1;
        }
        else if (c is DataGrid)
        {
            DataGrid dg = (DataGrid)c;
            dg.Controls.Clear();
        }
        // etc....
    }
}

这是并不是特别高贵找方法,但你的code。在您的网页/控制现在是更加简洁

It is not particularly elegent looking method but your code in your page/control is now the more succinct

foreach (Control c in myUserControl.Controls) {
    c.Clear();
}

和你当然可以,现在叫 control.Clear()在你任何地方都code。

and you can of course now call control.Clear() anywhere else in you code.

这篇关于我怎样才能动态地清除用户控件的所有控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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