I have a tab control and 3 tabpages in it. ( C#)
if i am in tab 2, and edit a text box value and then click tab 3, i need to validate what was enetered in the text box. if correct i should allow to to switch to tab 3 else should remain in tab 2 it self how do i achieve this?
iam curently handling the "leave" event of the tabpage2, i validate the text box value there and if found invalid i set as tabcontrol.Selectedtab = tabpage2; this does the validation but switches to new tab! how could i restrict the navigation.
I am a novice to C#, so may be i am handling a wrong event!
Here is the relevant code:
开发者_运维知识库private void tabpage2_Leave(object sender, EventArgs e)
{
if (Validatetabpage2() == -1)
{
this.tabcontrol.SelectedTab =this.tabpage2;
}
}
While the other approaches may work, the Validating event is designed specifically for this.
Here's how it works. When the SelectedIndex of the tab control changes, set the focus to the newly selected page and as well as CausesValidation = true. This ensures the Validating event will called if the user tries to leave the tab in any way.
Then do your normal validation in a page specific Validating event and cancel if required.
You need to make sure to set the initial selected tab page in the Form Shown event (Form_Load will not work) and also wire up the tab page specific validating events.
Here's an example:
private void Form_Shown(object sender, System.EventArgs e)
{
// Focus on the first tab page
tabControl1.TabPages[0].Focus();
tabControl1.TabPages[0].CausesValidation = true;
tabControl1.TabPages[0].Validating += new CancelEventHandler(Page1_Validating);
tabControl1.TabPages[1].Validating += new CancelEventHandler(Page2_Validating);
}
void Page1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text == "")
{
e.Cancel = true;
}
}
void Page2_Validating(object sender, CancelEventArgs e)
{
if (checkBox1.Checked == false)
{
e.Cancel = true;
}
}
private void tabControl1_SelectedIndexChanged(object sender, System.EventArgs e)
{
// Whenever the current tab page changes
tabControl1.TabPages[tabControl1.SelectedIndex].Focus();
tabControl1.TabPages[tabControl1.SelectedIndex].CausesValidation = true;
}
You can use the TabControl Selecting event to cancel switching pages. Setting e.Cancel to true in the event stops the tabcontrol from selecting a different tab.
private bool _cancelLeaving = false;
private void tabpage2_Leave(object sender, EventArgs e)
{
_cancelLeaving = Validatetabpage2() == -1;
}
private void tabcontrol_Selecting(object sender, TabControlCancelEventArgs e)
{
e.Cancel = _cancelLeaving;
_cancelLeaving = false;
}
精彩评论