Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I prevent the user from changing the selected tab page in a TabControl?

You can use the TabPage's Validating event to prevent a new tab page selection. Here are the steps:

1) Every time the user selects a new tab, make sure that the corresponding tab page gets the focus. You can do so as follows:

private void tabControl1_SelectedIndexChanged( object sender, EventArgs e )
{
  tabControl1.TabPages[ tabControl1.SelectedIndex ].Focus();
  tabControl1.TabPages[ tabControl1.SelectedIndex ].CausesValidation = true;
}

Note that CausesValidation should be set to True since you will be listening to the Validating event in the next step. You will also have to add some code like above when the TabControl is shown the very first time (like in the Form_Load event handler).

2) Listen to the TabPage's Validating event (which will be called when the user clicks on a different tab page) and determine whether the user should be allowed to change the selected tab page.

using System.ComponentModel;

private void tabPage1_Validating( object sender, CancelEventArgs e )
{
  if ( !checkValidated.Checked )
    e.Cancel = true;
}

Contributed from George Shepherd's Windows Forms FAQ