我怎样才能动态地清除用户控件的所有控件?
是否可以动态地(和一般)清除所有的用户控件的子控件的状态? (例如,所有的文本框,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.