代码之家  ›  专栏  ›  技术社区  ›  Steven

运行时清除ASP.NET窗体

  •  3
  • Steven  · 技术社区  · 16 年前

    在运行时使用c_清除ASP.NET窗体最简单的方法是什么?

    谢谢 服务提供商

    2 回复  |  直到 14 年前
        1
  •  1
  •   Mikael Svenson    16 年前

    我假设您希望清除输入框、下拉列表等。这可以通过以下方式在代码中递归清除所有数据。

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

    和递归函数

    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 );
        }
    }
    
        2
  •  0
  •   Steven    16 年前

    我已使用以下JS/C清除表单。

    C添加JS调用onload

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

    JS清除表单

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