在tabcontrol中获取控件

时间:2010-01-08 15:23:03

标签: .net tabcontrol

如何到达tabcontrol中的控件,我想用简单的foreach方法将所有文本框颜色变为颜色:

           foreach (Control c in this.Controls)
           {
//btw I get the next error at this line: System.Windows.Forms.TabControl' is a 'type', which is not valid in the given context  
              if (c == System.Windows.Forms.TabControl)
              {
                 c.BackColor = Color.FromArgb(240, 240, 240);
              }
           }

           for (int i = 0; i < this.Controls.Count; i++)
           {
              if (this.Controls[i].GetType().ToString() == "System.Windows.Forms.Textbox")
              {
                 this.Controls[i].BackColor = Color.FromArgb(240, 240, 240);
              }
           }

有人可以帮助我更改两个代码之一

2 个答案:

答案 0 :(得分:1)

您需要导航更多的控件嵌套,而您正在寻找的运算符(以消除错误)是isas运算符:

是:http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx

as:http://msdn.microsoft.com/en-us/library/cscsdfbt(VS.71).aspx

foreach (Control c in this.Controls)
{
    TabControl tabControl = c as TabControl;
    if (tabControl != null)
    {
        foreach (TabPage page in tabControl.TabPages)
        {
            foreach (Control innerControl in page.Controls)
            {
                if (innerControl is TextBox)
                {
                    innerControl.BackColor = Color.FromArgb(240, 240, 240);
                }
            }                        
        }
    }
}

答案 1 :(得分:0)

          if (c == System.Windows.Forms.TabControl)
          {
             c.BackColor = Color.FromArgb(240, 240, 240);
          }

可以

完成
TabControl tc = c as TabControl;
if(tc != null)
{
   tc.BackColor = Color.FromArgb(240, 240, 240);
}