JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Selecting and Replacing Text in a Text Box

To work with part of the text in a text box, you select the text you want using three properties:

  • SelectionLength— Returns or sets the number of characters selected.

  • SelectionStart— Returns or sets the starting point of text selected; indicates the position of the insertion point if no text is selected.

  • SelectedText— Returns or sets the string containing the currently selected text; consists of a zero-length string ("") if no characters are selected.

For example, here's how we select all the text in a text box and replace it with "Hello from Visual Basic". Note the use of the Len function to get the length of the text currently in the text box:

Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
    TextBox1.SelectionStart = 0
    TextBox1.SelectionLength = Len(TextBox1.Text)
    TextBox1.SelectedText = "Hello from Visual Basic"
End Sub

That's how it works when you want to select some text—you specify the beginning of the selected text in SelectionStart, the end in SelectionLength, and refer to the text with the SelectedText property. Note that text selected under program control this way does not appear highlighted in the text box; when the user selects text, the text will appear highlighted, and these properties will be set automatically.

Main Page

The HideSelection Property

While on the topic of text selection, we might note the HideSelection property, which, when True, turns off text selection highlighting when your program loses the focus.

Previous Section Next Section

JavaScript Editor Free JavaScript Editor     JavaScript Editor