tags:

views:

509

answers:

4

How can i remove the tabs from tabcontrol when i reference each tab to the childform.

I am using a tabcontrol, i want to remove a particular tab from the control. The value i have to do this in a string which i dynamically.

How to remove the tab from tabcontrol using a existing tab name which i have in a string ??

I tried something like...

 string tabToRemove = "tabPageName";
for (int i = 0; i < myTabControl.TabPages.Count; i++)
{
if (myTabControl.TabPages[i].Name.Equals(tabToRemove, StringComparison.OrdinalIgnoreCase))
{
    myTabControl.TabPages.RemoveAt(i);
    break;
}

}

But in the above code, the myTabControl.TabPages.Count is always zero.

Below is the code, to show i am creating the tabs. This is working perfectly.


         public void TabIt(string strProcessName)

        {
                    this.Show();

                    //Creating MDI child form and initialize its fields
                    MDIChild childForm = new MDIChild();
                    childForm.Text = strProcessName;
                    childForm.MdiParent = this;

                    //child Form will now hold a reference value to the tab control
                    childForm.TabCtrl = tabControl1;

                    //Add a Tabpage and enables it
                    TabPage tp = new TabPage();

                    tp.Parent = tabControl1;
                    tp.Text = childForm.Text;
                    tp.Show();
                    //child Form will now hold a reference value to a tabpage
                    childForm.TabPag = tp;
                    //Activate the MDI child form
                    childForm.Show();
                    childCount++;

                    //Activate the newly created Tabpage.
                    tabControl1.SelectedTab = tp;
                    tabControl1.ItemSize = new Size(200, 32);
                    tp.Height = tp.Parent.Height;
                    tp.Width = tp.Parent.Width;
        }


      public void GetTabNames()

      {

foreach (string strProcessName in Global.TabProcessNames)

                    {
                        TabIt(strProcessName);
                    }
        }


The child form :


using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
using System.Drawing.Drawing2D;

namespace Daemon
{
    /// <summary>
    /// Summary description for MDIChild.
    /// </summary>
    /// 

    public class MDIChild : System.Windows.Forms.Form
    {
     /// <summary>
     /// Required designer variable.
     /// </summary>
     private System.ComponentModel.Container components = null;
     private TabControl tabCtrl;
     private TabPage tabPag;

     public MDIChild()
     {
      //
      // Required for Windows Form Designer support
      //
      InitializeComponent();
            //MDIChild TargerForm = new MDIChild();
            //WinApi.SetWinFullScreen(TargerForm.Handle); 
      //
      // TODO: Add any constructor code after InitializeComponent call
      //
     }

     /// <summary>
     /// Clean up any resources being used.
     /// </summary>
     protected override void Dispose( bool disposing )
     {
      if( disposing )
      {
       if(components != null)
       {
        components.Dispose();
       }
      }
      base.Dispose( disposing );
     }

     public TabPage TabPag
     {
      get
      {
       return tabPag;
      }
      set
      {
       tabPag = value;
      }
     }

     public TabControl TabCtrl
     {
      set
      {
       tabCtrl = value;
      }
     }


     #region Windows Form Designer generated code
     /// <summary>
     /// Required method for Designer support - do not modify
     /// the contents of this method with the code editor.
     /// </summary>
     private void InitializeComponent()
     {
            this.SuspendLayout();
            // 
            // MDIChild
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.BackColor = System.Drawing.SystemColors.InactiveCaptionText;
            this.ClientSize = new System.Drawing.Size(0, 0);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "MDIChild";
            this.Opacity = 0;
            this.ShowIcon = false;
            this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
            this.Text = "MDIChild"; 
            this.Activated += new System.EventHandler(this.MDIChild_Activated);
            this.Closing += new System.ComponentModel.CancelEventHandler(this.MDIChild_Closing);
            this.ResumeLayout(false);

     }
     #endregion

     private void MDIChild_Closing(object sender, System.ComponentModel.CancelEventArgs e)
     {
            try
            {
                //Destroy the corresponding Tabpage when closing MDI child form
                this.tabPag.Dispose();

                //If no Tabpage left
                if (!tabCtrl.HasChildren)
                {
                    tabCtrl.Visible = false;
                }
            }
            catch (Exception ex)
            { 
            }
     }

     private void MDIChild_Activated(object sender, System.EventArgs e)
     {
            try
            {
                //Activate the corresponding Tabpage
                tabCtrl.SelectedTab = tabPag;

                if (!tabCtrl.Visible)
                {
                    tabCtrl.Visible = true;
                }
                Global.ExistingTabProcessNames.Add(tabPag.Text);
            }
            catch (Exception ex)
            { 
            }
     }

    }
}
+1  A: 

For starters you should be looping the other way around:

for (int i = myTabControl.TabPages.Count - 1; i >= 0 ; i--)
{
   ......
}

EDIT: Ignore me. I missed the break; and yes it should also be >= :(

My next theory is you are missing this line:

 // add the page to the tab control
 tabControl1.Controls.Add(tp);

PS: Why does copying code from SO not maintain the CRLFs. That is very annoying!

jussij
Why would this matter? And it would be i >= 0
SwDevMan81
Imagine you have two tabs with an index 0 and 1. So your loop would hopefully go from i = 0 to i = 1. But as soon as you remove the first tab, the second tab who's index was 1 is now 0 and no longer 1.
jussij
Getting error :InvalidArgument=Value of -1 not valid for index
Anuya
I used this code in the form where i have Tabcontrol. Or should i do it in the ChildForm ??
Anuya
That would make a difference if the OP didnt just break out as soon as they were done.
SwDevMan81
@jussij, getting error in this line-------------if (myTabControl.TabPages[i].Name.Equals(tabToRemove, StringComparison.OrdinalIgnoreCase))
Anuya
As you said the myTabControl.TabPages.Count = 0 and I suspect that is the error. Where in the code are your pages added to the tab control?
jussij
You shouldnt get that far, the loop shouldnt even run if Count is 0 because -1 is less than zero
SwDevMan81
@jussij, you can see the code in my question. GetTabNames() and TabIt(string strProcessName) are my functions to create tabs in tabcontrol. which is working correctly.
Anuya
You may have created the page and then shown the page, but did you tell C# that the tab control owns the page (i.e do you have the call to Controls.Add somewhere in your code?)
jussij
@jussij, i added this line -> tabControl1.Controls.Add(tp);Now i am getting two sets of tabs. It is creating two tabs with the same name, instead of one.
Anuya
So uncomment the code that creates the second tab (i.e. leave the creation of the pages up to the tab control). If you don't add the pages to the tab control then the count will always be 0.
jussij
@jussij, if that is the case, then the tabpages.count should show me the count after i add to the tabcontrols right??But even if i add -> tabControl1.Controls.Add(tp); the count remains zero !!!
Anuya
tabControl1.TabPages.Count is zero?
SwDevMan81
@jussij, If i add -> int iCount = tabcontrol1.tabpages.count insideTabit(), i am getting the count. But why i am not getting the count outside the function ???
Anuya
@SwDevMan81, YES - tabControl1.TabPages.Count is zero
Anuya
Where do you call GetTabNames() ?
SwDevMan81
@SwDevMan81, GetTabNames() is in a timertick event, for every 10 secs it will check against the arraylist which consist of tabnames and create a tab. i am doing this because, the arraylist values are dynamic and it shud get updated as tabs. Any problem with this ?
Anuya
I've used always tabControl1.Controls.Add(tp) but you could try using tabControl1.TabPages.Add(tp) instead. If that still results in tabControl1.TabPages.Count == 0 then I give up.
jussij
+1  A: 

I dont know the purpose of your code, but if you will eventually re-add the tab, why not just hide it? Its easier and you dont have to worry about reverse loop logic and invalid arguments once the page is hidden and such. If you need to need a way to address all the tabs at once just do a check for visible tabs...

ecathell
A: 

I would recommend taking a look at this tab page example for adding/removing tabs.

SwDevMan81
+1  A: 

As jussij suggested, you need to do this:

tabControl1.Controls.Add(tp);

And you can more easily locate the tab like this:

var foundTab = (from System.Windows.Forms.TabControl tab in tabControl1.TabPages.Cast<TabPage>()
                where tab.Name == "tabName"
                select tab).First();
jasonh
@jasonh, i tried to do above, i am getting error on tabControl1.TabPages -> Error -> Could not find an implementation of the query pattern for source type 'System.Windows.Forms.TabControl.TabPageCollection'. 'Where' not found. Consider explicitly specifying the type of the range variable 'tab'.
Anuya
Hmmm. I'm not sure why, so I started another question to see why that happens: http://stackoverflow.com/questions/1523457/why-doesnt-this-linq-query-work. In the mean time, you can use `tabControl1.TabPages.IndexOfKey("nameOfTabPageToDelete")` to get the index of the tab page you want to delete.
jasonh
Or, simply call `tabControl1.TabPages.RemoveByKey("nameOfTabPageToDelete")`
jasonh
According to those that answered my question, I've revised the answer above.
jasonh
Error Target : TSource First[TSource](System.Collections.Generic.IEnumerable`1[TSource]) ----------Error Message : Sequence contains no elements
Anuya
@jasonh, i am experiencing the above error.
Anuya
Then you're back to square one, having nothing in the collection in the first place. Are you sure you're adding the page to the `Controls` collection of the Tab Control?
jasonh
@Jasonh, let me make it clear, i dint add --- tabControl1.Controls.Add(tp); --- since it is duplicating. Shud i add this now ? ----- And i added the query in the function where i need to remove the tab. Is that correct ?
Anuya
@Jasonh, which line i should comment, in order to avoid duplicate tabs from the Tabit() function in my question ?
Anuya
@Jasonh, any hope ?
Anuya
I'm sorry, but I'm looking at all the code examples you've provided and I'm not seeing anywhere where you've called either `.Controls.Add` or `.TabPages.Add` on the Tab Control. That would be why the collection is empty.Yes, the query goes into the function that you use to remove the tab page.
jasonh
@jasonh, Please note that the tabcontrol is referenced to to a form called MDIchild. I have also pasted the code in that form in my question. Anything because of that ?
Anuya
But in order to enumerate the tab pages from a tab control, you have to add them to the TabControl's `Control` or `TabPages` collection. I don't see that happening after `TabPage tp = new TabPage()`.
jasonh