abacles abacles - 1 year ago 142
Vb.net Question

Cannot set focus to textbox

I am using VB and trying to select a portion of the text in a textbox of a separate form. However, I can't seem to find a good way to access the textbox from the other form, although the textbox is public (I am new to VB).

Currently, I'm trying to do this by calling a function located in the form (the form with the textbox), and then focusing on the textbox and selecting/highlighting the text. But it still doesn't work:

Public Sub GetFindLoc(ByVal lngStart As Long, ByVal intLen As Integer)
txtNotes.Select(lngStart, intLen)
End Sub

With this, I first hide the original form, and then try to select the text, and bring back the form. It shows that the active form is the one which I'm trying to select the text on, but it returns false on CanFocus().

Any help would be appreciated, thank you!

Answer Source

Hmm. This was more fiddly than I thought. You need to pass a reference to the other form:

Main form:

Public Class frmNotes
  'This is the main form
  'This form has a textbox named txtNotes and a button called btnShowFind
  'txtNotes has .MultiLine=True

  Private mfrmFind As frmFind
  Private Sub btnShowFind_Click(sender As Object, e As EventArgs) Handles btnShowFind.Click
    If mfrmFind Is Nothing OrElse mfrmFind.IsDisposed Then
      mfrmFind = New frmFind(Me)
    End If
  End Sub
End Class

Finder form:

Public Class frmFind
  'This form has a textbox called txtFind and a button called btnFind
  Private mfrmParent As frmNotes
  Sub New(parent As frmNotes)

    ' This call is required by the designer.

    ' Add any initialization after the InitializeComponent() call.
    mfrmParent = parent
  End Sub

  Private Sub btnFind_Click(sender As Object, e As EventArgs) Handles btnFind.Click
    If txtFind.Text = "" Then
      MsgBox("Please enter text to find", MsgBoxStyle.Exclamation)
      Exit Sub
    End If
    Dim intSearchBegin As Integer = mfrmParent.txtNotes.SelectionStart + 1
    Dim intStart As Integer = mfrmParent.txtNotes.Text.IndexOf(txtFind.Text, intSearchBegin)
    If intStart > -1 Then
      mfrmParent.txtNotes.Select(intStart, txtFind.Text.Length)
      mfrmParent.txtNotes.Select(0, 0)
      MsgBox("No more matches")
    End If
  End Sub
End Class
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download