TextBox In C#

510 View    Dec 11 2019 11:15PM

Creating a TextBox

We can create a TextBox control using a Forms designer at design-time or using the TextBox class in code at run-time (also known as dynamically).

To create a TextBox control at design-time, you simply drag and drop a TextBox control from Toolbox to a Form in Visual Studio. After you drag and drop a TextBox on a Form, the TextBox looks like Figure 1. Once a TextBox is on the Form, you can move it around and resize it using the mouse and set its properties and events.

Creating a TextBox

Creating a TextBox control at run-time is merely a work of creating an instance of TextBox class, setting its properties and adding TextBox class to the Form controls.

The first step to create a dynamic TextBox is to create an instance of TextBox class. The following code snippet creates a TextBox control object.
  1. // Create a TextBox object  
  2. TextBox dynamicTextBox = newTextBox();  
In the next step, you may set properties of a TextBox control. The following code snippet sets background color, foreground color, Text, Name, and Font properties of a TextBox.
  1. // Set background and foreground  
  2. dynamicTextBox.BackColor = Color.Red;  
  3. dynamicTextBox.ForeColor = Color.Blue;  
  4. dynamicTextBox.Text = "I am Dynamic TextBox";  
  5. dynamicTextBox.Name = "DynamicTextBox";  
  6. dynamicTextBox.Font = newFont("Georgia", 16);  
Once a TextBox control is ready with its properties, next step is to add the TextBox control to the Form. To do so, we use Form.Controls.Add method. The following code snippet adds a TextBox control to the current Form.
  1. Controls.Add(dynamicTextBox);  
Setting TextBox Properties

After you place a TextBox control on a Form, the next step is to set properties.

The easiest way to set properties is from the Properties Window. You can open Properties window by pressing F4 or right click on a control and select Properties menu item. The Properties window looks like Figure 2.

TextBox Properties

Location, Height, Width, and Size

The Location property takes a Point that specifies the starting position of the TextBox on a Form. The Size property specifies the size of the control. We can also use Width and Height property instead of Size property. The following code snippet sets Location, Width, and Height properties of a TextBox control.
  1. // Set TextBox properties  
  2. dynamicTextBox.Location = newPoint(20, 150);  
  3. dynamicTextBox.Height = 40;  
  4. dynamicTextBox.Width = 300;  
Multiline TextBox

By default, a TextBox control accepts input in a single line only. To make it multi-line, you need to set Multiline property to true. By default, the Multiline property is false.

When you drag and drop a TextBox control from Toolbox to a Form, you cannot change the height of a TextBox control. 

Text Box

But if you select a TextBox control and click on Tasks handle and check MultiLine CheckBox, you will see height resizing grip handles are available on a TextBox and you can resize the height of a control. 

Multiline TextBox
You can do this dynamically by setting Multiline property to true.
  1. // Make TextBox multiline  
  2. dynamicTextBox.Multiline = true;  
Background, Foreground, BorderStyle

BackColor and ForeColor properties are used to set background and foreground color of a TextBox respectively. If you click on these properties in Properties window, the Color Dialog pops up.

Alternatively, you can set background and foreground colors at run-time. The following code snippet sets BackColor and ForeColor properties.
  1. // Set background and foreground  
  2. dynamicTextBox.BackColor = Color.Red;  
  3. dynamicTextBox.ForeColor = Color.Blue;  
You can also set borders style of a TextBox by using the BorderStyle property. The BorderStyle property is represented by a BorderStyle enumeration that has three values – FixedSingle, Fixed3D, and None. The default value of border style is Fixed3D. The following code snippet sets the border style of a TextBox to FixedSingle.
  1. dynamicTextBox.BorderStyle = BorderStyle.FixedSingle;  

Name property represents a unique name of a TextBox control. It is used to access the control in the code. The following code snippet sets and gets the name and text of a TextBox control.
  1. dynamicTextBox.Name = "DynamicTextBox";  
  2. string name = dynamicTextBox.Name;  
Text, TextAlign, and TextLength

Text property of a TextBox represents the current text of a TextBox control. The TextAlign property represents text alignment that can be Left, Center, or Right. The TextLength property returns the length of a TextBox contents.

The following code snippet sets the Text and TextAlign properties and gets the size of a TextBox control.
  1. dynamicTextBox.Text = "I am Dynamic TextBox";  
  2. dynamicTextBox.TextAlign = HorizontalAlignment.Center;  
  3. int size = dynamicTextBox.TextLength;  
Append Text

One way to append text to a TextBox is simply set Text property to current text plus new text you would want to append something like this.
  1. textBox1.Text += " Appended text";  
TextBox also has the ApendText method to do the same. The AppendText method appends text at the end of a TextBox. The following code snippet uses AppendText method to append text to the textBox1 contents.
  1. textBox1.AppendText(" Appended text");  
AcceptsReturn and AcceptsTab

In a Multiline TextBox control, you need to press CTRL+ENTER to create a new line. The AcceptsReturn property sets TextBox control to move to new line by simply pressing ENTER key. By default, AcceptsReturn property of a TextBox control is false.
  1. // accepts ENTER key  
  2. dynamicTextBox.AcceptsReturn = true;  
If a TextBox control is set to multiline, the AcceptsTab property is used to set so the TextBox control accepts TAB key. If this property is not set, pressing TAB key simply move to the next control on a Form. By default, AcceptsTab property value of a TextBox control is false.
  1. // accepts TAB key  
  2. dynamicTextBox.AcceptsTab = true;  
If WordWrap property is true, the text in the TextBox control automatically wraps to the next line if required. If . If this property is set to true, horizontal scroll bars are not displayed regardless of the ScrollBars property setting.
  1. // Wordwrap  
  2. dynamicTextBox.WordWrap = true;  

A Multiline TextBox control can have scrollbars. The ScrollBars property of TextBox control is used to show scrollbars on a control. The ScrollBars property is represented by a ScrollBars enumeration that has four values – Both, Vertical, Horizontal, and None.

The following code snippet makes both vertical and horizontal scrollbars active on a TextBox control and they will be visible when the scrolling is needed on a TextBox control.
  1. dynamicTextBox.ScrollBars = ScrollBars.Both;  

Font property represents the font of text of a TextBox control. If you click on the Font property in Properties window, you will see Font name, size and other font options. The following code snippet sets Font property at run-time.
  1. dynamicTextBox.Font = newFont("Georgia", 16);  
Password Character and Character Casing

PasswordChar property is used to apply masking on a TextBox when you need to use it for a password input and do now what password to be readable. For example, you can place a star (*) for password characters.

The following code snippet sets a dollar ($) symbol as any character entered in a TextBox.
  1. dynamicTextBox.PasswordChar = '$';  
UseSystemPasswordChar property is used to full default system password If the UseSystemPasswordChar is set to true, the default system password character is used and any character set by PasswordChar is ignored.

CharacterCasing property of TextBox sets the case of text in a TextBox, It has three values – Upper, Lower, and Normal.
  1. dynamicTextBox.CharacterCasing = CharacterCasing.Upper;  
Read TextBox Contents

The simplest way of reading TextBox control contents is using the Text property. The following code snippet reads contents of a TextBox in a string.
  1. string textBoxContents = dynamicTextBox.Text;  
In a multiline TextBox, if the TextBox contents are separated by multiple lines and you want to read contents of a TextBox line by line, you can use the Lines property of the TextBox. The Lines property returns an array of strings where each element of the returned array is a line.

The following code snippet reads a TextBox contents line by line.
  1. string [] textBoxLines = dynamicTextBox.Lines;  
  2. foreach (string line in textBoxLines)  
  3. {  
  4.    MessageBox.Show(line);  
  5. }  
Maximum Length

You can restrict the number of characters in a TextBox control by setting MaxLength property. The following code snippet sets the maximum length of a TextBox to 50 characters.
  1. dynamicTextBox.ReadOnly = true;  
  2. dynamicTextBox.MaxLength = 50;  

You can make a TextBox control read-only (non-editable) by setting the ReadOnly property to true. The following code snippet sets the ReadOnly property to true.
  1. dynamicTextBox.ReadOnly = true;  
Enabling and Disabling Shortcuts

ShortcutsEnabled property of the TextBox is used to enable or disable shortcuts. By default, shortcuts are enabled. The following code snippet disables shortcuts in a TextBox.
  1. dynamicTextBox.ShortcutsEnabled = false;  
ShortcutsEnabled property applies to the following shortcut key combinations:
  • CTRL+Z
  • CTRL+E
  • CTRL+C
  • CTRL+Y
  • CTRL+X
  • CTRL+V
  • CTRL+A
  • CTRL+L
  • CTRL+R
Selection in TextBox

SelectedText property returns the selected text in a TextBox control. 
  1. string selectedText = dynamicTextBox.SelectedText;  
You may also use SelectionStart and SelectionLength properties to get and set the selected text in a TextBox. The SelectionStart property represents the starting index of the selected text and SelectionLength property represents the number of characters to be selected after the starting character. The following code snippet sets the selection on a TextBox. 
  1. dynamicTextBox.SelectionStart = 10;  
  2. dynamicTextBox.SelectionLength = 20;  
Clear, SelectAll and DeselectAll

Clear method removes the contents of a TextBox. The following code snippet uses Clear method to clear the contents of a TextBox.
  1. textBox1.Clear();  
TextBox class provides SelectAll and DeselectAll methods to select and deselect all text of a TextBox control. The following code snippet shows how to use SelectAll and DeselectAll methods.
  1. privatevoid selectAllToolStripMenuItem_Click(object sender, EventArgs e) {  
  2.     if (textBox1.TextLength > 0) textBox1.SelectAll();  
  3. }  
  4. privatevoid deselectAllToolStripMenuItem_Click(object sender, EventArgs e) {  
  5.     if (textBox1.TextLength > 0) textBox1.DeselectAll();  
  6. }  
Cut, Copy, Paste, Undo Operations in TextBox

TextBox class provides Cut, Copy, Paste, and Undo methods to cut, copy, paste, and undo clipboard operations. The following code snippet shows how to use Cut, Copy, Paste, and Undo methods.
  1. privatevoid cutToolStripMenuItem_Click(object sender, EventArgs e) {  
  2.     if (textBox1.SelectionLength > 0) textBox1.Cut();  
  3. }  
  4. privatevoid copyToolStripMenuItem_Click(object sender, EventArgs e) {  
  5.     if (textBox1.SelectionLength > 0) textBox1.Copy();  
  6. }  
  7. privatevoid pasteToolStripMenuItem_Click(object sender, EventArgs e) {  
  8.     if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text)) {  
  9.         textBox1.Paste();  
  10.     }  
  11. }  
  12. privatevoid undoToolStripMenuItem_Click(object sender, EventArgs e) {  
  13.     if (textBox1.CanUndo) {  
  14.         textBox1.Undo();  
  15.         textBox1.ClearUndo();  
  16.     }  
  17. }  

A TextBox control accepts user input on a Form. In this article, we discussed how to create a TextBox control in Windows Forms at design-time as well as run-time. After that, we saw how to use various properties and methods.