如何从代码隐藏中清除所有表单字段?

Sla*_*uma 5 asp.net webforms

HTML有一个输入按钮类型,可以在一个步骤中将表单中的所有字段重置为初始状态:<input type="reset" ... />.

是否有类似的简单方法从代码隐藏重置aspx页面的所有表单字段?或者是需要重置所有控件一个个TextBox1.Text=string.Empty,TextBox2.Text=string.Empty等等?

提前致谢!

更新:

上下文是一个简单的联系人/"向我们发送消息"页面,页面上有8个asp:TextBoxes(用户输入名称,地址,电话,电子邮件,消息等).然后他点击提交,代码隐藏中的Onclick消息处理程序向某个管理员发送一封电子邮件,用户填写的所有表单字段都应该清空,并在标签中收到通知("Message sent blabla ..." ).我希望清除表单字段以避免用户再次单击"提交"并再次发送相同的消息.

Tho*_*mas 11

您只需要为每种类型的控件编写一个fork,除非其中一个控件有一些特殊的东西需要重置它.

foreach( var control in this.Controls )
{
    var textbox = control as TextBox;
    if (textbox != null)
        textbox.Text = string.Empty;

    var dropDownList = control as DropDownList;
    if (dropDownList != null)
        dropDownList.SelectedIndex = 0;
    ...
}
Run Code Online (Sandbox Code Playgroud)

添加您询问如何清除控件甚至是埋藏的控件.要做到这一点,你应该创建一个递归例程,如下所示:

private void ClearControl( 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;
    ...

    foreach( Control childControl in control.Controls )
    {
        ClearControl( childControl );
    }
}
Run Code Online (Sandbox Code Playgroud)

所以,你可以通过传递页面来调用它:

ClearControls( this );
Run Code Online (Sandbox Code Playgroud)


Kam*_*tap 7

有关更多信息,请参阅此链接

http://www.freshcodehub.com/Article/3/clear-all-fields-like-textbox-dropdownlist-checkbox-radiobutton-label-after-form-submission-in-aspnet-c

public void ClearControls(Control parent)
{
    foreach (Control c in parent.Controls)
    {
        if ((c.GetType() == typeof(TextBox)))  //Clear TextBox
        {
            ((TextBox)(c)).Text = "";
        }
        if ((c.GetType() == typeof(DropDownList)))  //Clear DropDownList
        {
            ((DropDownList)(c)).ClearSelection();
        }
        if ((c.GetType() == typeof(CheckBox)))  //Clear CheckBox
        {
            ((CheckBox)(c)).Checked = false;
        }
        if ((c.GetType() == typeof(CheckBoxList)))  //Clear CheckBoxList
        {
            ((CheckBoxList)(c)).ClearSelection();
        }
        if ((c.GetType() == typeof(RadioButton)))  //Clear RadioButton
        {
            ((RadioButton)(c)).Checked = false;
        }
        if ((c.GetType() == typeof(RadioButtonList)))  //Clear RadioButtonList
        {
            ((RadioButtonList)(c)).ClearSelection();
        }
        if ((c.GetType() == typeof(HiddenField)))  //Clear HiddenField
        {
            ((HiddenField)(c)).Value = "";
        }
        if ((c.GetType() == typeof(Label)))  //Clear Label
        {
            ((Label)(c)).Text = "";
        }
        if (c.HasControls())
        {
            ClearControls(c);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)