Live Chat Icon For mobile
Live Chat Icon

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

Platform: WinForms| Category: 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:


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

’VB.Net
Private  Property sender,() As tabControl1_SelectedIndexChanged(object
End Property
Private Function e)() As System.EventArgs
	tabControl1.TabPages(tabControl1.SelectedIndex).Focus()
	tabControl1.TabPages(tabControl1.SelectedIndex).CausesValidation = True
End Function

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.


// In C#
private void tabPage1_Validating(object sender, 
System.ComponentModel.CancelEventArgs e)
{
	if(!checkValidated.Checked)
		e.Cancel = true;
}

’ In VB.Net
Private  Sub tabPage1_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs)
	If Not checkValidated.Checked Then
		e.Cancel = True
	End If
End Sub

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.