views:

56

answers:

2

Howto reach the controls in a tabcontrol, I want to color all the textboxen into a color with a simple foreach method:

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

Could someone help my change one of the two codes

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

Could be done as

TabControl tc = c as TabControl;
if(tc != null)
{
   tc.BackColor = Color.FromArgb(240, 240, 240);
}
taylonr
+1  A: 

You'll need to navigate a little more control nesting, and the operators you are looking for (to remove the error) are the is and as operators:

is: 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);
                }
            }                        
        }
    }
}
Dave