我的一個form中有很多的textbox,現在要把所有的text屬性值為空:
原來這樣操作:txtid.text="";
              txtname.text="";
              .
              .
              .
效率太低,請問高手,如何通過更少的語句,可以達到同樣的效果??謝謝!

解决方案 »

  1.   

    private void button1_Click(object sender, System.EventArgs e)
    {
    ControlCollection cc = (System.Windows.Forms.Form.ControlCollection)this.Controls;
    foreach (Control ctrl in cc)
    {
    if (ctrl is TextBox)
    {
    ((TextBox)ctrl).Text = string.Empty;
    }
    }
    }
      

  2.   

    //如果所有的textbox都在form上(没有在其它容器控件内)用这个就行
    foreach (Control obj in this.Controls)
                {
                    if (obj.GetType() == typeof(TextBox))
                    {
                        ((TextBox)obj).Text = "";
                    }
                }
      

  3.   

    否则,用这个,
        private void button1_Click(object sender, EventArgs e)
            {
                
                foreach (Control obj in this.Controls)
                {
                    test(obj);
                }        }        private void test(Control controls)
            {
                if (controls.HasChildren)
                {
                    foreach (Control control in controls.Controls)
                    {
                        test(control);
                    }
                }
                else
                {
                    if (controls.GetType() == typeof(TextBox))
                    {
                        ((TextBox)controls).Text = "";
                    }
                }
            }
      

  4.   


    foreach (Control ctl in this.Controls)
    {
        if(ctl is TextBox)
            (ctl as TextBox).Text = "";
    }