Cómo ocultar TabPage de TabControl [duplicar]


Esta pregunta ya tiene una respuesta aquí:

¿Cómo ocultar TabPage de TabControl en WinForms 2.0?

Author: Tomasz Smykowski, 2009-02-16

22 answers

No, esto no existe. Tienes que quitar la pestaña y volver a añadirla cuando quieras. O utilice un control de pestaña diferente (3rd-party).

 125
Author: Marc Gravell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-16 08:20:23

Fragmento de código para Ocultar una TabPage

private void HideTab1_Click(object sender, EventArgs e)
{
    tabControl1.TabPages.Remove(tabPage1);
}

Fragmento de código para Mostrar una TabPage

private void ShowTab1_Click(object sender, EventArgs e)
{
    tabControl1.TabPages.Add(tabPage1);
}
 86
Author: moonshine,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-22 11:04:49

La propiedad Visiblity no se ha implementado en las páginas de tabulación, y tampoco hay un método Insert.

Debe insertar y eliminar manualmente las páginas de pestañas.

Aquí hay un trabajo para lo mismo.

Http://www.dotnetspider.com/resources/18344-Hiding-Showing-Tabpages-Tabcontrol.aspx

 29
Author: amazedsaint,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-16 09:49:56

Me doy cuenta de que la pregunta es vieja, y la respuesta aceptada es vieja, pero ...

Al menos en .NET 4.0...

Para ocultar una pestaña:

tabControl.TabPages.Remove(tabPage);

Para devolverlo:

tabControl.TabPages.Insert(index, tabPage);

TabPages funciona mucho mejor que Controls para esto.

 26
Author: Jesse Chisholm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-13 04:30:53

Variante 1

Para evitar el klikering visual es posible que necesite usar:

bindingSource.RaiseListChangeEvent = false 

O

myTabControl.RaiseSelectedIndexChanged = false

Eliminar una página de pestañas:

myTabControl.Remove(myTabPage);

Añadir una página de pestaña:

myTabControl.Add(myTabPage);

Inserte una página de pestaña en una ubicación específica:

myTabControl.Insert(2, myTabPage);

No se olvide de reverenciar los cambios:

bindingSource.RaiseListChangeEvent = true;

O

myTabControl.RaiseSelectedIndexChanged = true;

Variante 2

myTabPage.parent = null;
myTabPage.parent = myTabControl;
 18
Author: profimedica,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-21 11:01:16

Las soluciones proporcionadas hasta ahora son demasiado complicadas. Lea la solución más fácil en: http://www.codeproject.com/Questions/614157/How-to-Hide-TabControl-Headers

Puede usar este método para hacerlos invisibles en tiempo de ejecución:

private void HideAllTabsOnTabControl(TabControl theTabControl)
{
  theTabControl.Appearance = TabAppearance.FlatButtons;
  theTabControl.ItemSize = new Size(0, 1);
  theTabControl.SizeMode = TabSizeMode.Fixed;
}
 13
Author: mas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-07 21:04:11
private System.Windows.Forms.TabControl _tabControl;
private System.Windows.Forms.TabPage _tabPage1;
private System.Windows.Forms.TabPage _tabPage2;

...
// Initialise the controls
...

// "hides" tab page 2
_tabControl.TabPages.Remove(_tabPage2);

// "shows" tab page 2
// if the tab control does not contain tabpage2
if (! _tabControl.TabPages.Contains(_tabPage2))
{
    _tabControl.TabPages.Add(_tabPage2);
}
 5
Author: Nasuh Levent YILDIZ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-10 16:53:00

Crea una nueva clase vacía y pasa esto dentro de ella:

using System.Windows.Forms;

namespace ExtensionMethods
{
    public static class TabPageExtensions
    {

        public static bool IsVisible(this TabPage tabPage)
        {
            if (tabPage.Parent == null)
                return false;
            else if (tabPage.Parent.Contains(tabPage))
                return true;
            else
                return false;
        }

        public static void HidePage(this TabPage tabPage)
        {
            TabControl parent = (TabControl)tabPage.Parent;
            parent.TabPages.Remove(tabPage);
        }

        public static void ShowPageInTabControl(this TabPage tabPage,TabControl parent)
        {
            parent.TabPages.Add(tabPage);
        }
    }
}

2-Añadir referencia al espacio de nombres ExtensionMethods en el código del formulario:

using ExtensionMethods;

3 - Ahora puedes usar yourTabPage.IsVisible(); para comprobar su visibilidad, yourTabPage.HidePage(); para ocultarla, y yourTabPage.ShowPageInTabControl(parentTabControl); para mostrarla.

 4
Author: Mhdali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-20 08:12:55

Combiné la respuesta de @Jack Griffin y la de @amazedsaint ( el fragmento de código dotnetspider respectivamente) en una única TabControlHelper.

El TabControlHelper le permite:

  • Mostrar / Ocultar todas las páginas de pestañas
  • Mostrar / Ocultar páginas de una sola pestaña
  • Mantenga la posición original de las páginas de pestañas
  • Intercambiar páginas de pestañas

public class TabControlHelper
{
    private TabControl _tabControl;
    private List<KeyValuePair<TabPage, int>> _pagesIndexed;
    public TabControlHelper(TabControl tabControl)
    {
        _tabControl = tabControl;
        _pagesIndexed = new List<KeyValuePair<TabPage, int>>();

        for (int i = 0; i < tabControl.TabPages.Count; i++)
        {
            _pagesIndexed.Add(new KeyValuePair<TabPage, int> (tabControl.TabPages[i], i ));
        }
    }

    public void HideAllPages()
    {
        for (int i = 0; i < _pagesIndexed.Count; i++)
        {
            _tabControl.TabPages.Remove(_pagesIndexed[i].Key);
        }
    }

    public void ShowAllPages()
    {
        for (int i = 0; i < _pagesIndexed.Count; i++)
        {
            _tabControl.TabPages.Add(_pagesIndexed[i].Key);
        }
    }

    public void HidePage(TabPage tabpage)
    {
        if (!_tabControl.TabPages.Contains(tabpage)) return;
        _tabControl.TabPages.Remove(tabpage);
    }

    public void ShowPage(TabPage tabpage)
    {
        if (_tabControl.TabPages.Contains(tabpage)) return;
        InsertTabPage(GetTabPage(tabpage).Key, GetTabPage(tabpage).Value);
    }

    private void InsertTabPage(TabPage tabpage, int index)
    {
        if (index < 0 || index > _tabControl.TabCount)
            throw new ArgumentException("Index out of Range.");
        _tabControl.TabPages.Add(tabpage);
        if (index < _tabControl.TabCount - 1)
            do
            {
                SwapTabPages(tabpage, (_tabControl.TabPages[_tabControl.TabPages.IndexOf(tabpage) - 1]));
            }
            while (_tabControl.TabPages.IndexOf(tabpage) != index);
        _tabControl.SelectedTab = tabpage;
    }

    private void SwapTabPages(TabPage tabpage1, TabPage tabpage2)
    {
        if (_tabControl.TabPages.Contains(tabpage1) == false || _tabControl.TabPages.Contains(tabpage2) == false)
            throw new ArgumentException("TabPages must be in the TabControls TabPageCollection.");

        int Index1 = _tabControl.TabPages.IndexOf(tabpage1);
        int Index2 = _tabControl.TabPages.IndexOf(tabpage2);
        _tabControl.TabPages[Index1] = tabpage2;
        _tabControl.TabPages[Index2] = tabpage1;
    }

    private KeyValuePair<TabPage, int> GetTabPage(TabPage tabpage)
    {
        return _pagesIndexed.Where(p => p.Key == tabpage).First();
    }
}
 4
Author: Bruno Bieri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-06 09:00:24
    public static Action<Func<TabPage, bool>> GetTabHider(this TabControl container) {
        if (container == null) throw new ArgumentNullException("container");

        var orderedCache = new List<TabPage>();
        var orderedEnumerator = container.TabPages.GetEnumerator();
        while (orderedEnumerator.MoveNext()) {
            var current = orderedEnumerator.Current as TabPage;
            if (current != null) {
                orderedCache.Add(current);
            }
        }

        return (Func<TabPage, bool> where) => {
            if (where == null) throw new ArgumentNullException("where");

            container.TabPages.Clear();
            foreach (TabPage page in orderedCache) {
                if (where(page)) {
                    container.TabPages.Add(page);
                }
            }
        };
    }

Úsalo así:

    var hider = this.TabContainer1.GetTabHider();
    hider((tab) => tab.Text != "tabPage1");
    hider((tab) => tab.Text != "tabpage2");

El orden original de las pestañas se mantiene en una Lista que está completamente oculta dentro de la función anonymous. Mantenga una referencia a la instancia de la función y conservará su orden de pestañas original.

 1
Author: Rob,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-14 04:41:33

Puede establecer el padre de la tabpage en null para ocultar y para mostrar sólo establecer tabpage padre a la tabcontrol

 1
Author: Abuleen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-16 16:49:56

Bueno, si no quieres estropear el código existente y solo quieres ocultar una pestaña, puedes modificar el código generado por el compilador para comentar la línea que añade la pestaña al tabcontrol.

Por ejemplo: La siguiente línea agrega una pestaña llamada "readformatcardpage" a un Tabcontrol llamado "tabcontrol"

Esto.tabcontrol.Controles.Añadir (esto.readformatcardpage);

Lo siguiente evitará la adición de la pestaña a la tabcontrol

//esto.tabcontrol.Controles.Añadir (esto.readformatcardpage);

 1
Author: user720694,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-01 13:32:29

+1 para microsoft: -).
Me las arreglé para hacerlo de esta manera :
(asume que tiene un botón' Siguiente ' que muestra la siguiente tabpage-tabSteps es el nombre del control de tabulación)
Al iniciar, guarde todas las páginas de pestañas en una lista adecuada . Cuando el usuario presiona el botón Siguiente, elimine todas las páginas de pestañas en el control de pestañas, luego añadir que con el índice adecuado:

        int step = -1;
        List<TabPage> savedTabPages;

        private void FMain_Load(object sender, EventArgs e) {
            // save all tabpages in the list
            savedTabPages = new List<TabPage>();
            foreach (TabPage tp in tabSteps.TabPages) {
                savedTabPages.Add(tp);
            }
            SelectNextStep();
        }

        private void SelectNextStep() {
            step++;
            // remove all tabs
            for (int i = tabSteps.TabPages.Count - 1; i >= 0 ; i--) {
                    tabSteps.TabPages.Remove(tabSteps.TabPages[i]);
            }

            // add required tab
            tabSteps.TabPages.Add(savedTabPages[step]);
        }

        private void btnNext_Click(object sender, EventArgs e) {
            SelectNextStep();
        }

Actualización

public class TabControlHelper {
    private TabControl tc;
    private List<TabPage> pages;
    public TabControlHelper(TabControl tabControl) {
        tc = tabControl;
        pages = new List<TabPage>();
        foreach (TabPage p in tc.TabPages) {
            pages.Add(p);
        }
    }

    public void HideAllPages() {
        foreach(TabPage p in pages) {
            tc.TabPages.Remove(p);
        }
    }

    public void ShowAllPages() {
        foreach (TabPage p in pages) {
            tc.TabPages.Add(p);
        }
    }

    public void HidePage(TabPage tp) {
        tc.TabPages.Remove(tp);
    }        

    public void ShowPage(TabPage tp) {
        tc.TabPages.Add(tp);
    }
}  
 1
Author: Jack Griffin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-30 10:18:12

Como un trabajo barato, he utilizado una etiqueta para cubrir las pestañas que quería ocultar.

Entonces podemos usar el prop visible de la etiqueta como sustituto. Si alguien sigue esta ruta, no olvide manejar los trazos del teclado o los eventos de visibilidad. No querrías que las teclas de cursor izquierda y derecha expongan la pestaña que estás tratando de ocultar.

 0
Author: Kevin Godwin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-06 12:34:08

No estoy seguro acerca de "Winforms 2.0" pero esto es probado y probado:

Http://www.mostthingsweb.com/2011/01/hiding-tab-headers-on-a-tabcontrol-in-c /

 0
Author: Jake,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-08 18:37:07

En WPF, es bastante fácil:

Asumiendo que le has dado un nombre al TabItem, por ejemplo,

<TabItem Header="Admin" Name="adminTab" Visibility="Hidden">
<!-- tab content -->
</TabItem>

Podría tener lo siguiente en el código detrás del formulario:

 if (user.AccessLevel == AccessLevelEnum.Admin)
 {
     adminTab.Visibility = System.Windows.Visibility.Visible;
 }

Debe tenerse en cuenta que se ha creado un objeto User llamado user con su propiedad AccessLevel establecida en uno de los valores de enumeración definidos por el usuario de AccessLevelEnum... lo que sea; es solo una condición por la cual decido mostrar la pestaña o no.

 0
Author: Jim Daehn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-14 18:23:32

Yo también tenía esta pregunta. TabPage.Visible no se implementa como se indicó anteriormente, lo que fue de gran ayuda (+1). Encontré que puedes anular el control y esto funcionará. Un poco de necroposting, pero pensé en publicar mi solución aquí para otros...

    [System.ComponentModel.DesignerCategory("Code")]
public class MyTabPage : TabPage
{
    private TabControl _parent;
    private bool _isVisible;
    private int _index;
    public new bool Visible
    {
        get { return _isVisible; }
        set
        {
            if (_parent == null) _parent = this.Parent as TabControl;
            if (_parent == null) return;

            if (_index < 0) _index = _parent.TabPages.IndexOf(this);
            if (value && !_parent.TabPages.Contains(this))
            {
                if (_index > 0) _parent.TabPages.Insert(_index, this);
                else _parent.TabPages.Add(this);
            }
            else if (!value && _parent.TabPages.Contains(this)) _parent.TabPages.Remove(this);

            _isVisible = value;
            base.Visible = value;
        }
    }

    protected override void InitLayout()
    {
        base.InitLayout();
        _parent = Parent as TabControl;
    }
}
 0
Author: John S.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-20 18:11:03
    TabPage pageListe, pageDetay;
    bool isDetay = false;
    private void btnListeDetay_Click(object sender, EventArgs e)
    {
        if (isDetay)
        {
            isDetay = false;
            tc.TabPages.Remove(tpKayit);
            tc.TabPages.Insert(0,pageListe);
        }
        else
        {
            tc.TabPages.Remove(tpListe);
            tc.TabPages.Insert(0,pageDetay);
            isDetay = true;
        }
    }
 0
Author: AlataliHasan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-14 19:04:01

He utilizado el mismo enfoque, pero el problema es que cuando la página de pestañas se eliminó de la lista de páginas de pestañas de control de pestañas, también se elimina de la lista de controles de página de pestañas. Y no se dispone cuando se dispone la forma.

Así que si tiene muchas páginas de pestañas "ocultas", puede obtener el error superado de cuota de controlador de Windows y solo el reinicio de la aplicación lo solucionará.

 0
Author: oleksa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-02 14:14:01

Si está hablando de AjaxTabControlExtender, establezca TabIndex de cada pestaña y establezca la propiedad visible True/False de acuerdo con su necesidad.

MyTab.Tabs [1].Visible = true / false;

 0
Author: Minhajul Islam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-01 06:06:19
// inVisible
TabPage page2 = tabControl1.TabPages[0];
page2.Visible= false;
//Visible 
page2.Visible= true;
// disable
TabPage page2 = tabControl1.TabPages[0];
page2.Enabled = false;
// enable
page2.Enabled = true;
//Hide
tabCtrlTagInfo.TabPages(0).Hide()
tabCtrlTagInfo.TabPages(0).Show()

Simplemente copie,pegue y pruébelo, el código anterior ha sido probado en vs2010, funciona.

 -2
Author: sree ranjith c.k,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-25 09:13:42

Ocultar TabPage y Eliminar el encabezado:

this.tabPage1.Hide();
this.tabPage3.Hide();
this.tabPage5.Hide();
tabControl1.TabPages.Remove(tabPage1);
tabControl1.TabPages.Remove(tabPage3);
tabControl1.TabPages.Remove(tabPage5);

Mostrar TabPage y Visible el Encabezado:

tabControl1.TabPages.Insert(0,tabPage1);
tabControl1.TabPages.Insert(2, tabPage3);
tabControl1.TabPages.Insert(4, tabPage5);
this.tabPage1.Show();
this.tabPage3.Show();
this.tabPage5.Show();
tabControl1.SelectedTab = tabPage1;
 -2
Author: ISB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-13 12:59:07