循环整个控件代码该如何写foreach (Control ctl in this.Controls)
            {
                ctl = null;
            }
我想把所有的控件都置为NULL
但以上的代码是错误的,该如何修正呢. 

解决方案 »

  1.   

    foreach (System.Windows.Forms.Control control in this.Controls)//遍历Form上的所有控件   
       {   
        if (control is System.Windows.Forms.PictureBox)   
        {   
         System.Windows.Forms.PictureBox pb = (System.Windows.Forms.PictureBox)control;   
         pb.AllowDrop = true;   
        }   
       }  
      

  2.   

    怎么这么复杂,我只想把文本框上的数值全部为NULL,要写 这么多吗
      

  3.   

    所有控件都设置为null...你什么意识呢...是把窗体从控件上删除还是别的什么?
      

  4.   

    在foreach的时候不能修改循环项的值,所以将ctrl=null是错误的,需要改变的话可以使用for循环;
    你的需求:
    private void SetTextBoxEmpty(Control control)
    {
      if(control.Controls.Count == 0) retrun;
      foreach(Control ctrl in control.Controls)
      {
        if(ctrl is TextBox)
        {
           (ctrl as TextBox).Text = "";//将文本置空
        }
        SetTextBoxEmpty(ctrl);//递归调用本方法,保证遍历所有控件
      }
    }在最初调用的地方,将this作为参数传给上述方法即可。
      

  5.   

    foreach应该可以改吧。
    里面加个判断。
    如果 if(ctl is TextBox)的话,TextBox.Text = null,应该可以吧。
    我也刚学。在网吧上网。没试过。错了不要见怪。
      

  6.   

    其中 control.Controls 这句不行,
      

  7.   

     private void toolStripButton1_Click(object sender, EventArgs e)
            {
                foreach (Control ctl in Controls)
                {
                    if (ctl is TextBox)
                    {
                        ctl.Text = null;
                    }
                }
            }
    你看,这是我设计的,好简单的话,就搞定了,看来我还是有点头脑的
      

  8.   

    foreach(Contorl ctl in this.Contorls)
    {
      if(ctl is TextBox)
      {
        ctl.Text = null;
      }
    }
    昨天回去试了。可以。
    但是感觉有点不严谨的样子。
    刚学。只会这样做了。