Home > Mobile >  How can I use tag to hide/show controls in TabControl C#
How can I use tag to hide/show controls in TabControl C#

Time:04-18

I have a TabControl MyTabs contains some labels and textboxes , I am trying to hide/show controls in MyTabs and show/hide pages based on RadioButton check :

private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
    foreach (var Ctrl in MyTabs.Controls.OfType<TextBox>())
    {
        if (Ctrl.Tag.ToString() == "Products")

        {
            Ctrl.Visible = false;
            PgBom.Hide();
        }
        else
        {
            Ctrl.Visible = true;
            PgBom.Show();
        }
    }

    foreach (var Ctrl in MyTabs.Controls.OfType<Label>())
    {
        if (Ctrl.Tag.ToString() == "Products")

        {
            Ctrl.Visible = false;
            PgBom.Hide();
        }
        else
        {
            Ctrl.Visible = true;
            PgBom.Show();
        }
    }


}

PgBom is a page in MyTabs , What is wrong with my code ? . Thanks in advance.

CodePudding user response:

I am pretty sure that the Controls in a TabControl will be TabPages. Controls like labels and text boxes would go into a specific TabPage. Therefore, to get the controls, then you need to loop through all the different TabPages then look at each TabPages Controls collection as shown below.

Also, setting the variable to… PgBom.Show(); and PgBom.Hide(); is questionable in sense that as you loop through the controls it may get hid and un-hid many times over. What ends up being displayed will depend on what the LAST checked control’s state was.

foreach (TabPage tp in MyTabs.TabPages) {
  foreach (var Ctrl in tp.Controls.OfType<TextBox>()) {
    if (Ctrl.Tag != null) {
      if (Ctrl.Tag.ToString() == "Products") {
        Ctrl.Visible = false;
        PgBom.Hide();
      }
      else {
        Ctrl.Visible = true;
        PgBom.Show();
      }
    }
  }
  foreach (var Ctrl in tp.Controls.OfType<Label>()) {
    if (Ctrl.Tag != null) {
      if (Ctrl.Tag.ToString() == "Products") {
        Ctrl.Visible = false;
        PgBom.Hide();
      }
      else {
        Ctrl.Visible = true;
        PgBom.Show();
      }
    }
  }
}
  • Related