Clear asp.net form at runtime

The easiest way to clear an asp.net form at runtime using C #.

Thanks Sp

+3
source share
2 answers

I used the following JS / C # to clean the form.

C # to add onload js call

  Page.ClientScript.RegisterStartupScript(typeof(WebForm3), "ClearPage", "ClearForm();", true);

Js to clean form

function ClearForm() {
            var AllControls = document.getElementById('ctl00_ContentPlaceHolder1_PnlAll')
            var Inputs = AllControls.getElementsByTagName('input');
            for (var y = 0; y < Inputs.length; y++) {
                // define element type
                type = Inputs[y].type
                // alert before erasing form element
                //alert('form='+x+' element='+y+' type='+type);
                // switch on element type
                switch (type) {
                    case "text":
                    case "textarea":
                    case "password":
                        //case "hidden":
                        Inputs[y].value = "";
                        break;



                }
            }


        }
0
source

I assume that you want to clear input fields, dropdowns, etc. This can be done as follows in code to recursively clear all data.

foreach( var control in this.Controls )
{
   ClearControl( control );
}

and recursive function

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;

    // handle any other control //

    foreach( Control childControl in control.Controls )
    {
        ClearControl( childControl );
    }
}
+1
source

Source: https://habr.com/ru/post/1748193/


All Articles