Search code examples
c#labeltabcontroltabpage

change Text of several labels located on a Tab control using loop in C#


I have a windows form project ( Net 4) in C#, and I want to change all of my label.Texts in a loop. but my labels are in a Tabcontrol (in tabpage 4) and i don't know what to do. my labels name are label1 label2 and so.. until label 100.


Solution

  • You could use something like this to loop through the controls and set the label text based on the number in the name.

    foreach ( Control ctrl in tabPage4.Controls )
    {
      if ( ctrl.GetType().Equals(typeof(Label)) )
      {
        string strName = ctrl.Name;
        if ( strName.StartsWith("label", StringComparison.InvariantCultureIgnoreCase) )
        {
          string strNum = strName.Substring(5);
          int iIndex;
          if ( int.TryParse(strNum, out iIndex) )
          {
            ctrl.Text = "your text";
          }
        }
      }
    }