What is the Required trick to Programmatically remove the last Tab Page from a Tab Control

Answered Closed
0
0

I have tried setting the SelectedTab to Null before trying to remove last TabPage  from the collection

I have tried setting the Selected index to -1 before trying to remove the last TabPage from the collection

each resulting in error

tab.Dispose(); works when multiple tabs are open, closing the one found,   as selected.

but it does not work on the last (or a single) open tab.

private void btnCloseTab_Click(object sender, EventArgs e)
{
if (tabMain.SelectedTab != null)
{
// First Find selected Tab
var tab = tabMain.SelectedTab;

if (tabMain.TabPages.Count == 1)
{
//tabMain.SelectedIndex = -1;

// release Selected Tab
tabMain.SelectedTab = null;

// there was code here to just Remove the Tab by found “tab” variable

//which also bombs
tabMain.TabPages.Clear();  // still errors
}
else
{
tabMain.TabPages.Remove(tab);
tab.Dispose();
}
}
}

  • Christian Programmer
    ERROR: Index -1 is out of range. Parameter name: index
  • Christian Programmer
    Immediate window  results of attempt to manually set SelectedIndex to -1 ( releasing the selected tabPage at Position ZERO )   from being selected.. I thought this might allow me to then remove it from the TabPage collection  since its no longer the active selected but of course its still selected  as I can’t set selectedIndex  to    -1 or unselect the selected tab …   I am assuredly GUESSING that these set properties  are hindering the removal of the tab .. 
  • Christian Programmer
    This worked for me : my delegated event still being ( in play ) as assigned to the btnCloseTab_Click was forcing the index of last tab control from 0 to -1 thus breaking stuff, even when I captured the tab control before trying to set its SelectedIndex. private void btnCloseTab_Click(object sender, EventArgs e) { tabMain.SelectedIndexChanged -= ActiveTabIndexChange; if (tabMain.SelectedTab != null) { var tab = tabMain.SelectedTab; if (tabMain.TabPages.Count == 1) { tabMain.SelectedIndex = -1; tabMain.TabPages.Clear(); tab.Dispose(); // tabMain.Refresh(); } else { tabMain.TabPages.Remove(tab); tab.Dispose(); } } tabMain.SelectedIndexChanged += ActiveTabIndexChange; }
  • You must to post comments
Best Answer
0
0

What is the issue? I tried and it works perfectly. Attach a test case showing the error in case you need further assistance.

  • You must to post comments
0
0

 

Immediate window  results of attempt to manually set SelectedIndex to -1 ( releasing the selected tabPage at Position ZERO )   from being selected..

I thought this might allow me to then remove it from the TabPage collection

since its no longer the active selected

but of course its still selected  as I can’t set selectedIndex  to    -1

or unselect the selected tab …   I am assuredly GUESSING that these set properties

are hindering the removal of the tab ..

 

  • You must to post comments
Showing 2 results