0

Currently I am using this method to highlight text inside a TextBox, but it works just sometimes.

This code has to verify if there is contained a space in the entered text. If there is a space in the text the user should be warned, and then the text inside the TextBox has to be highlighted:

if (textBox.Text.Contains(" "))
{
    MessageBox.Show("Sorry, the value entered must not contain any spaces.", "Please enter a valid value", MessageBoxButton.OK, MessageBoxImage.Error);

    //Highlights incorrect text
    textBox.SelectionStart = 0;
    textBox.SelectionLength = textBox.Text.Length;
}

Why isn't this method working for me all the time and what can I do to fix it?

Community
  • 1
  • 1
Eric after dark
  • 1,768
  • 4
  • 31
  • 79

1 Answers1

0

It might be a problem when you are selecting length of textBox which has no focus in current moment.

Can you try to add check for focus?

if (textBox.Text.Contains(" "))
{
    MessageBox.Show("Sorry, the value entered must not contain any spaces.", "Please enter a valid value", MessageBoxButton.OK, MessageBoxImage.Error);

    if(!textBox.Focused)
    {
      textBox.Focus();
    }

    //Highlights incorrect text
    textBox.SelectionStart = 0;
    textBox.SelectionLength = textBox.Text.Length;
}

Also instead of current solution you can use textBox.SelectAll():

if (textBox.Text.Contains(" "))
{
    textBox.SelectAll();
    MessageBox.Show("Sorry, the value entered must not contain any spaces.", "Please enter a valid value", MessageBoxButton.OK, MessageBoxImage.Error);

}
Dmitry Zaets
  • 3,289
  • 1
  • 20
  • 33