We help IT Professionals succeed at work.

vb.net vs2013 Setfocus not working

José Perez
José Perez asked
on
Hi, I am having issues to set focus on a textbox. What happens is that when the textbox is empty or null I would like to set the focus on the textbox so the user can add the text. Currently it is not doing it.
The code is the following:

 If (IsNumeric(txtPrecioCompetencia1.Text) = False) Then
            MessageBox.Show("Favor ingrese precio de Competencia 1")
            txtPrecioCompetencia1.Focus()

        ElseIf (String.IsNullOrEmpty(txtPrecioCompetencia1.Text) = False) Then
            MessageBox.Show("Favor ingrese precio de Competencia 1")
            txtPrecioCompetencia1.Focus()
        End If

Open in new window

Comment
Watch Question

Top Expert 2015

Commented:
You should not use Focus in .NET. According to the documentation: Focus is a low-level method intended primarily for custom control authors. Instead, application programmers should use the Select method or the ActiveControl property for child controls, or the Activate method for forms.

Author

Commented:
Tried both recommendations... still not working, my Textbox1 control still not focused.
Top Expert 2015

Commented:
Reading carefully your code, it looks as if you inverted the logic in String.IsNullOrEmpty(txtPrecioCompetencia1.Text) = False

This means that it will trigger when the control is not NullOrEmpty. I understand that you want the reverse. Simply remove = False.

Author

Commented:
ok it (more or less) works. Now it gives the 2 textbox messages instead of giving the first textbox message and focus on this textbox.

        If (IsNumeric(txtPrecioCompetencia1.Text)) Then
            MessageBox.Show("Favor ingrese precio de Competencia 1")
            txtPrecioCompetencia1.Select()

        ElseIf (String.IsNullOrEmpty(txtPrecioCompetencia1.Text)) Then
            MessageBox.Show("Favor ingrese precio de Competencia 1")
            txtPrecioCompetencia1.Select()
        End If

        If (IsNumeric(txtPrecioCompetencia2.Text)) Then
            MessageBox.Show("Favor ingrese precio de Competencia 2")
            txtPrecioCompetencia2.Select()
        ElseIf (String.IsNullOrEmpty(txtPrecioCompetencia2.Text)) Then
            MessageBox.Show("Favor ingrese precio de Competencia 2")
            txtPrecioCompetencia2.Select()
        End If

Open in new window

Top Expert 2015
Commented:
Put an Exit Sub (or Exit Function) after the Select statements in the first block. It will skip the second one if both needs to trigger.