Search code examples
c#tabcontroltabpage

TabPages in accordance to CheckedListBox


I have a tabcontrol with 4 tabpages.I have a Checked list box with 8 items.I want to open the tabpages which were checked in the checkedlistbox.I tried like this.

      private void clbScenario_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        if (clbScenario.SelectedIndex == 0 || clbScenario.SelectedIndex == 1 || clbScenario.SelectedIndex == 2 || clbScenario.SelectedIndex == 3 || clbScenario.SelectedIndex == 4)
        {
            tabControl1.TabPages.Add(tp1);

        }
        else
            HideTabPage(tp1);
        if (clbScenario.SelectedIndex == 5 || clbScenario.SelectedIndex == 8)
        {
            tabControl1.TabPages.Add(tp2);
            //ShowTabPage(tp2);
        }
        else
            HideTabPage(tp2);
        if (clbScenario.SelectedIndex == 6)
        {
            tabControl1.TabPages.Add(tp3);

        }
        else
            HideTabPage(tp3);
        if (clbScenario.SelectedIndex == 7)
        {
            tabControl1.TabPages.Add(tp4);

        }
        else
            HideTabPage(tp4);
    }

But the result is not as i thought.Please help me anyone


Solution

  • You need to use ItemCheckEventArgs e not the CheckedListBox itself. e.index is gonna give you which item is checked/unchecked and e.CurrentValue is gonna give you wheter is checked/unchecked. What you need to consider is if the e.CurrentValue is unchecked that means it's actually gonna be checked because this is showing value of the control before the process.

    private void clbScenario_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        if (e.Index >= 0 && e.Index <= 4)
        {
            if (e.CurrentValue.ToString() == "Unchecked") tabControl1.TabPages.Add(tp1);
            else HideTabPage(tp1);
        }        
        else if (e.Index == 5 || e.Index == 8)
        {
            if (e.CurrentValue.ToString() == "Unchecked") tabControl1.TabPages.Add(tp2);
            else HideTabPage(tp2);
        }        
        else if (e.Index == 6)
        {
            if (e.CurrentValue.ToString() == "Unchecked") tabControl1.TabPages.Add(tp3);
            HideTabPage(tp3);
        }        
    
        else if (e.Index == 7)
        {
            if (e.CurrentValue.ToString() == "Unchecked") tabControl1.TabPages.Add(tp4);
            else HideTabPage(tp4);
        }
    }