Every Windows user is familiar with text boxes: they're exactly what their name implies: box-like controls in which you can enter text. Text boxes can be multiline, have scroll bars, be read-only, and have many other attributes, as we'll see in this chapter. (Not every Windows user is familiar with rich text boxes, on the other hand. Rich text boxes support not only plain text, but also rich text format [RTF] text.) The TextBox class is derived from the TextBoxBase class, which is based on Control:
Object MarshalByRefObject Component Control TextBoxBase TextBox
In fact, most of the functionality of the text box control is simply inherited from the TextBoxBase class, which is also a base class for the rich text box control.
Windows forms text boxes are used to get input from the user or to display text. The TextBox control is generally used for editable text, although it can also be made read-only. Text boxes can display multiple lines, wrap text to the size of the control, and add basic formatting, such as quotation marks and masking characters for passwords.
The text displayed by the control is contained in the Text property. By default, you can enter up to 2,048 characters in a text box. If you set the MultiLine property to True to make the control accept multiple lines of text, you can enter up to 32KB of text. The Text property can be set at design time with the Properties window, at run time in code, or by user input at run time. The current contents of a text box can be retrieved at run time by reading the Text property. We've seen how to do this already, as in this example, which inserts text into a text box:
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click TextBox1.Text = "Hello from Visual Basic" End Sub
You can set or read text from text boxes at run time, and the user can enter and edit text in text boxes as well. You can limit the amount of text entered into a TextBox control by setting the MaxLength property to a specific number of characters. TextBox controls also can be used to accept passwords if you use the PasswordChar property to mask characters.
You also can restrict text from being entered in a TextBox control by creating an event handler for the KeyDown event, letting you validate each character entered in the control. And you can restrict any data entry in a TextBox control by setting the ReadOnly property to True.