服务器端和客户端清除TextBox控件的值

客户端
<script language="javascript" type="text/javascript">
  function clearControl()
  {
        var Input=div1.getElementsByTagName("input");
       
        for(var i=0;i<Input.length;i++)
        {
        
            if(Input[i].type=="text")
            {
              
                Input[i].value="";
            }
        }
        return false;
 
  }

</script>
    <form id="form1" runat="server">
    <div>
        <div id="div1">
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
        </div>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return clearControl()" />
        <asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" /></div>
    </form>
直接在客户端调用了就清除了不要去服务器端
还有一种就是经过服务器然后在调用javascript比如注册成功后提示成功在清空TextBox 
protected void Button2_Click(object sender, EventArgs e)
    {
        ClientScriptManager cs = Page.ClientScript;
        Type type = Page.GetType();
        string key = "key";
        //判断是否已经注册
       
        if (!cs.IsClientScriptBlockRegistered(type, key))
        {
            //此方法是在一开始就加载此方法
            cs.RegisterClientScriptBlock(type, key, "alert('注册成功')", true);
        }
        if (!cs.IsStartupScriptRegistered(type, key))
        {
            //这个方法是在</from>结束标签后调用,因为在这里要调用div,所以要等这些控件加载后才能调用
           
            cs.RegisterStartupScript(type, key, "clearControl()", true);
        }
    }      
服务器端
定义一个方法做递归查找
 private void ClearControl(System.Web.UI.Control page)
    {
        int count = page.Controls.Count;
        for (int i = 0; i <count; i++)
        {
            foreach(System.Web.UI.Control con in page.Controls[i].Controls)
            {
                if(con.HasControls())
                {
                    ClearControl(con);
                }
                else
                {
                    if (con is TextBox)
                    {
                        (con as TextBox).Text = string.Empty;
                    }
                }
            }
           
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        ClearControl(Page);
    }

posted @ 2007-06-28 14:46  思然  阅读(830)  评论(1编辑  收藏  举报