How to clear all form fields from code-behind?

前端 未结 5 1429
日久生厌
日久生厌 2021-01-03 01:06

HTML has an input button type to reset all fields in a form to their initial state in one step: .

Is there a similar

5条回答
  •  时光取名叫无心
    2021-01-03 01:46

    You need only write a fork for each type of control unless one of the control has something special that needs to be done to reset it.

    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;
        ...
    }
    

    ADDITION You asked how to clear controls even ones that are buried. To do that, you should create a recursive routine like so:

    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 );
        }
    }
    

    So, you would call this by passing the page:

    ClearControls( this );
    

提交回复
热议问题