fbhdev
fbhdev

Reputation: 526

How can I cancel the selecting Event for a TabControl

I am handling tab change in the WinForms TabControl's Deselecting event. However, in some cases I am deleting the tab that I clicked on before I switch to it.

scenario

I have tab 1 and tab 2 currently I'm in tab 1 I click on tab 2 tab 1 Deselecting Event Removes Tab 2 from the tab collection Crashes at OnPaint because it's trying to go to a tab that no longer exists. (ArgumentOutOfRangeException). It crashes before it hits the Selecting Event.

I don't want to see if the tabcount changed in deselecting because I only want to cancel if the tab I'm going to no longer exists.

Any help would be greatly appreciated.

    private void TabControl_Deselecting( object sender, TabControlCancelEventArgs ) {
       DoSomeWork();
    }

Assume that DoSomeWork deletes the Tab I clicked on. How can I find out if it did delete the tab I was intending to go to?

Upvotes: 0

Views: 3803

Answers (2)

Hans Passant
Hans Passant

Reputation: 941277

No repro. The scenario is strange but I can't get it to crash. Do make sure you cancel the Deselect.

    private void tabControl1_Deselecting(object sender, TabControlCancelEventArgs e) {
        if (e.TabPageIndex == 0 && tabControl1.TabCount > 1) {
            tabControl1.TabPages[1].Dispose();
            e.Cancel = true;
        }
    }

Upvotes: 1

Tigran
Tigran

Reputation: 62248

One of possible solution that comes in my mind:

if you are sure that Tab1 Deselect event raised before Tab2 Select event, I would try, to declare my custom tab control and override it's OnPaintMethod, like this pseudocode:

public class MyCustomTab : TabItem
{
   ...


   protected override OnPaint(....)
   {
      if(this.Parent == null) return;

       base.Paint(...);
   }    
}

Clear that to your TabControl you should add TabItems of that type.

Upvotes: 0

Related Questions