C# 方法重置groupBox中的成员
groupBox是否有任何方法可以清除groupBox中对象的所有属性。例如,清除所有文本框,取消选中所有复选框等,并将它们设置为默认值。或者我应该一个接一个地编码来清除它们?我想在事件列表视图SelectedIndexChanged上执行此操作 更新: 好的,谢谢你的重播,我发现你可以很简单地选择groupbox里面的控件C# 方法重置groupBox中的成员,c#,reset,groupbox,C#,Reset,Groupbox,groupBox是否有任何方法可以清除groupBox中对象的所有属性。例如,清除所有文本框,取消选中所有复选框等,并将它们设置为默认值。或者我应该一个接一个地编码来清除它们?我想在事件列表视图SelectedIndexChanged上执行此操作 更新: 好的,谢谢你的重播,我发现你可以很简单地选择groupbox里面的控件 foreach (Control ctrl in groupBox2.Controls)//this will only select controls o
foreach (Control ctrl in groupBox2.Controls)//this will only select controls of groupbox2
{
if (ctrl is TextBox)
{
(ctrl as TextBox).Text = "";
}
if (ctrl is CheckBox)
{
(ctrl as CheckBox).Checked = false;
}
if (ctrl is ComboBox)
{
(ctrl as ComboBox).SelectedIndex = -1;
}
//etc
}
您需要逐个清除组框中的所有控件。最快的方法是:
Control myForm = Page.FindControl("Form1");
foreach (Control ctrl in myForm.Controls)
{
//Clears TextBox
if (ctrl is System.Web.UI.WebControls.TextBox)
{
(ctrl as TextBox).Text = "";
}
//Clears DropDown Selection
if (ctrl is System.Web.UI.WebControls.DropDownList)
{
(ctrl as DropDownList).ClearSelection();
}
//Clears ListBox Selection
if (ctrl is System.Web.UI.WebControls.ListBox)
{
(ctrl as ListBox).ClearSelection();
}
//Clears CheckBox Selection
if (ctrl is System.Web.UI.WebControls.CheckBox)
{
(ctrl as CheckBox).Checked = false;
}
//Clears RadioButton Selection
if (ctrl is System.Web.UI.WebControls.RadioButtonList)
{
(ctrl as RadioButtonList).ClearSelection();
}
//Clears CheckBox Selection
if (ctrl is System.Web.UI.WebControls.CheckBoxList)
{
(ctrl as CheckBoxList).ClearSelection();
}
}
您必须创建如下函数:
private void ClearControls(Control control)
{
var textbox = control as TextBox;
if (textbox != null)
textbox.Text = string.Empty;
var dropDownList = control as DropDownList;
if (dropDownList != null)
dropDownList.SelectedIndex = 0;
// And add any other controls
// ...
foreach( Control childControl in control.Controls )
{
ClearControl( childControl );
}
}
ClearControls(this);
就这样说吧:
private void ClearControls(Control control)
{
var textbox = control as TextBox;
if (textbox != null)
textbox.Text = string.Empty;
var dropDownList = control as DropDownList;
if (dropDownList != null)
dropDownList.SelectedIndex = 0;
// And add any other controls
// ...
foreach( Control childControl in control.Controls )
{
ClearControl( childControl );
}
}
ClearControls(this);
这将以递归方式工作,因此,如果您有任何面板(例如,有自己的控件集要清除),这也将清除这些面板。我已编辑了您的标题。请看,“,其中的共识是“不,他们不应该”。好的,谢谢你的信息,我下一步不会这么做@约翰索克。我想确保在我编写一堆你知道的代码之前没有任何方法没有Page.FindControl()方法。除了在元素中?还是我弄错了什么?