Question

I am binding textbox1 data on LostFocus event. I set keyboard navigation. Tabindex=7 for textbox1 and for textbox2 keyboardNavigation TabIndex=8. Now my problem is am doing regular expression validation for textbox1, if I enter invalid characters in textbox1 it displyas MessageBox saying not valid and as soon as click ok it will navigate to textbox2 where I want to set this keyboard navigation to textbox1 till i enter valid characters. How can i achieve this?

I tried this way:

if (!string.IsNullOrEmpty(txtbox1.Text))
{
    if(Regex.IsMatch(txtbox1.Text, @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"))
    {
        txtbox2.Text = "(" + txtbox1.Text + ")";
    }
    else
    {
        MessageBoxResult mbr;
        mbr=MessageBox.Show("please enter valid Email Id", "VMS", MessageBoxButton.OK, MessageBoxImage.Error);

        if (mbr == MessageBoxResult.OK)
        {
            Keyboard.Focus(txtbox1);
            txtbox1.Clear();
            // txtbox1.TabIndex = 7;
            //txtbox1.MoveFocus(new TraversalRequest(FocusNavigationDirection.Up));
            // txtbox2.MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));
        }

        //txtbox1.Focus();                

        // KeyboardNavigation.SetTabIndex(txtbox1, 6);
     }
}
else
{
    txtbox2.Text = string.Empty;
    // txtbox1.TabIndex = 7;
    //txtbox1.MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));
    //KeyboardNavigation.SetTabIndex(txtbox1, 7);
    // txtbox2.TabIndex=7;
    //Keyboard.Focus(txtbox2);
}

How can I set the keyboard navigation to txtbox1 if the text enter is invalid? Any suggestion.

EDIT: Added xaml

  <Window x:Class="DataBinding.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
<Grid>
    <TextBox Name="txtbox1" Margin="71,22,82,195" LostFocus="txtbox1_LostFocus" />
    <TextBox Name="txtbox2" Margin="71,96,82,127" />

</Grid>

Was it helpful?

Solution

Try going back a few steps... when I copied your code into a new project and added a couple of TextBoxes, it already does what you are after. The MessageBox popped up, I clicked OK and focus stayed in textBox1. This is the behaviour that I expected.

I suggest to you that it is your code elsewhere that is moving the logical focus to textBox2, maybe even a property that you set on the Window or UserControl that the TextBoxes reside in.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top