Home

Windows Controls: The Text Box

Introduction to Text Boxes

Description

A text box is a Windows control used to get or display text to the user. At its most regular use, a text box serves as a placeholder to fill out and provide information. Such a use is common on employment applications, login dialog boxes, forms, etc. Like most other controls, the role of a text box is not obvious at first glance; that is why it should be accompanied by a label that defines its purpose.

From the user's standpoint, a text box is named after the label closest to it. Such a label is usually positioned to the left or the top side of the text box. From the programmer's point of view, a text box is a placeholder used for various things. For example, you can show or hide it as you see fit. You can also use it only to display text without allowing the user to change it.

Creating a Text Box

To create a text box, from the Common Controls section of the Toolbox, you can click TextBox Text Box and click the form. The text box is based on the TextBox class. This means that you can use this class to dynamically create a text box and add it to your application. The text box control is based on the TextBox class whose immediate parent is TextBoxBase. Like every .NET Framework class, it has a constructor that can be used to dynamically create the control. The TextBoxBase class provides other methods derived from the control's parent or from ancestor classes.

Using the Text of a Text Box

Introduction

As a control primarily meant to display text, like a label, the text box shares many of the characteristics of a label: text alignment, font, color, etc.

The most important aspect of a text box is its text, whether it is displaying or requesting it. This is the Text property. When you add a text box control to a form or other container, by default, it is left empty. If you want the control to display some text when the form launches, type a string in the Text property field in the Properties window.

After creating a text box, it may be empty, the user can start typing in it to fill it with text. You can programmatically assign it a string to occupy it. Another way you can put or add text to the control is to paste the content of the clipboard, using text from another control. The syntax of the Paste() method is:

public void Paste();

At any time, to know the length of the text in the control, you can retrieve the value of the TextLength property, which is of type int.

Selecting Text

The selection of text from a text box control can be performed either by you or by a user. To select part of the text, you can specify the starting point using the SelectionStart property, which is of type int. After the starting position, you can specify the number of characters to include in the selection. This is done using the SelectionLength property, which is of type int. The SelectionStart and the SelectionLength properties allow you to programmatically select text. The user, on the other hand, also knows how to select part of the text of the control. These operations can also be performed using the Select() method of the TextBox class. Its syntax is:

public void Select(int start, int length);

Alternatively, the user may want to select the whole content of the control. To programmatically select the whole text of a text box control, call the SelectAll() method. Its syntax is:

public void SelectAll();

When  some text has been selected in the control, to get that text, you can retrieve the value of the SelectedText property, which is a handle to String.

Operations on Text

After the text, in part or in whole, has been selected, you or the user can manipulate it. For example, you can copy the selection to the clipboard. This is done using the Copy() method. Its syntax is:

public void Copy();

To delete part of the text, the user can cut it. You can programmatically do this using the Cut() method. Its syntax is:

public void Cut();

To delete the whole contents of the text box, you can call the Clear() method. Its syntax is:

public void Clear();

Any operation performed on the text box can be undone using the Undo() method whose syntax is:

public void Undo();

To prevent an undo operation, call the ClearUndo() method. Its syntax is:

public void ClearUndo();

Characteristics of Text Boxes

Mnemonics

As mentioned already, a text box should be accompanied by a label that indicates what it is used for. To support this relationship, the Label control provides various properties. An accelerator character is a symbol of the label that provides easy access to its text box. On the label, such a character is underlined. An example would be First Name. The idea is that, if the user presses the Alt key in combination with the label's underlined character, the text box it accompanies would receive focus.

To create an accelerator key, choose one of the label's characters and precede it with an ampersand character when setting its caption. An example would be &First Name. If you want a label to display the accelerator character instead of a plain ampersand, set the label's UseMnemonic property to true, which is already its default value. If you set it to true but need to display an ampersand, type two & characters where the ampersand would be shown.

The UseMnemonic property of a label is only used to indicate that the label would display an accelerator character and the & symbol typed on the label creates that accelerator character. To indicate which text box would receive focus when the accelerator character of the label is invoked, you must make sure you establish an appropriate tab sequence using the Tab Order menu item from the main menu or using the combination of TabStop/TabIndex properties. Typically, the label should have a Tab Order or TabIndex value that is just - 1 of that of the control it serves.

The Read-Only Property

By default, a newly created text box is used to both display and receive text from the user. If you want the user to read text without being able to change it, set the ReadOnly Boolean property to True. Its default value is false.

Auto-Completing a Text Box

If a text box allows the user to enter text in it, the user can click the control and start typing. If a certain text box usually receives some known or common strings, you can assist the user with completing the entry. The TextBox class supports this with three properties.

If you want to assist the user with completing the string entered in a text box, first specify where the necessary strings will come from. You have two options. You can use the AutoCompleteSource property, that is based on the AutoCompleteSource enumeration. Its members are: None, RecentlyUsedList, FileSystem, FileSystemDirectories, HistoryList, ListItems, AllSystemSources, AllUrl, and CustomSource.

If you want to specify your own-created list of items, use the AutoCompleteCustomSource property. At design time, to create a list of strings, access the Properties window for the text box. In the Properties window, click the ellipsis button of the AutoCompleteCustomSource field to open the String Collection Editor. Enter the strings separated by a hard Return, and click OK.

After specifying the source of the list that will assist the user to complete the entry of the text box, set it AutoCompleteMode property. This property is based on the AutoCompleteMode enumeration that has four members. None is the default value.

Character Casing

A text box can be configured to display only lowercase characters, only uppercase characters, or a mix. This characteristic is controlled by the CharacterCasing property, which is an enumerator that holds the same name. The default value of this property is Normal, which indicates that the control can use a mix of lowercase and uppercase characters. If you set this property to Lower, all existing characters, if any, in the control would be converted to lowercase and all future characters typed in the control would be automatically converted to lowercase. If you set this property to Upper, all existing characters, if any, in the control would be converted to uppercase and all future characters typed in the control would be automatically converted to uppercase.

Character Password

Text typed in a text box appears with its corresponding characters unless you changed the effect of the CharacterCasing property from its default Normal value. This allows the user to see, and be able to read, the characters of the control. If you prefer to make the characters un-readable, you have two options.

The operating system uses a default character it uses to hide the contents of a text box. If you want to use that character, set the UseSystemPasswordChar property to true. If you prefer to specify your own character, you can use the PasswordChar property. Although this property is a char type of data, changing it actually accomplishes two things:

The Multi-Line Text Box

Introduction

The regular text box is meant to display one line of text. If the user enters text and presses Enter, nothing particular happens. If the user enters text and presses Tab, the focus moves to the next control in the tab sequence. You may want to create an application that goes further than the one-line limit. For example, if you have used Notepad, you would know that it shares the font characteristics of a text box but it also allows some text navigation features that require more than one line. You can create such an application based on the text box control.

Creating a Multi-Line Text Box

The TextBox control is equipped with one particular property that, when considered, changes the control tremendously. This property is called Multiline. Multiline is a Boolean property whose default value is false. If it is set to a true value, it allows the control to display multiple lines of text, unlike the normal text box that can display only one line.

Characteristics of a Multi-Line Text Box

Introduction

The multi-line text box shares all of the properties of the single-line text box. These include the read-only attribute, the character casing, and the password options. Although these properties are valid, some of them may not be suitable for a multi-line text box, such as applying a password character to hide the text, trying to auto-complete a string while the user is typing it, etc. This is why, in most cases, we will tend to consider the single-line and the multiple line objects are separate controls.

The Lines of Text

By default, when you add a new text box to your form, it appears empty. When the application comes up, the user mostly reads and/or enters text in the multi-line text box when interacting with the control. At design time, you can set the text that would display when the multi-line text box comes up. To support multiple lines of text, the TextBox class is equipped with a property named Lines:

public string[] Lines { get; set; }

As you can see, the Lines proeprty is an array, which is also serializable. During design, to manually create the lines of text, in the Properties window, click the Lines field, then click its ellipsis button. That would open the String Collection Editor. Type the desired text and click OK. On the other hand, after the user has entered some text or a few lines of text in the control, it holds these lines. The lines of text of a text box are stored in an array represented by a property named Lines. This means that, at run time, you can create an array of lines of text and assign it to the text box. Or, to get the lines of text of the control, you can retrieve the value of the Lines property.

The Modified Attribute

When a multi-line text box opens, the compiler registers the content of the control. If the user has the ability to change the text in the control and if the user changes it, the compiler flags the control as Modified. This allows you to take actions. You can acknowledge this by programmatically setting the Modified property to true. If another control or some other action alters the contents of the multi-line text box, you can make sure that this property reflects the change. You can change this programmatically as follows:

private void button1_Click(object  sender, EventArgs  e)
{
    textBox1.Modified = true;
}

The Maximum Length of Text

The multi-line text box allows the user to enter up to 32767 characters. If you want to limit the maximum number of characters that the user can enter to a value lower than this, you can use the MaxLength property at design time. You can also change this programmatically. Here is an example:

private void button1_Click(object  sender, EventArgs  e)
{
    textBox1.MaxLength = 1020;
}

Using the Enter Key

If the control will be used to enter text, the user can press Enter at the end of a line to move to the next line. This ability is controlled by the Boolean AcceptsReturn property. By default, this property is set to False because this control is primarily created from a normal single-line TextBox control that has no formal action to take when the user presses Enter. If you are creating a multi-line text box and you expect your users to perform some type of text editing, you certainly should allow them to press Enter to move to the next line. Therefore, in most cases, when creating a multi-line text box, you should set its AcceptsReturn property to True. To set it programmatically, assign the desired value to the AcceptstReturn property. Here is an example:

private void button1_Click(object  sender, EventArgs  e)
{
        textBox1.AcceptsReturn = true;
}

Using the Tab Key

The user is accustomed to pressing Tab to insert tab characters in the text. By default, when the user presses Tab when interacting with your application, the focus moves from one control to the next, following the TabIndex values of the form. Even when using a multi-line text box to perform text editing, if the user presses Tab, the focus would switch to another control or to the form. If you want a multi-line text box to receive focus when the user presses the Tab key, set the AcceptTab property from False (the default), to True.

When entering text in a multi-line text box control, the characters start on the left side of the multi-line text box and are subsequently added on the right side. The ability to align text is controlled by the TextAlign property. For a multi-line text box control, the alignment is configured using the HorizontalAlignment enumerator.

Wrapping Text

As the user enters text in a multi-line text box box, the compiler considers that a paragraph starts from the user typing a character until he or she presses Enter. Therefore, a paragraph could be an empty space, a character, a word, a line of text, a whole page or an entire book. Depending on the width of the multi-line text box control, the text is incrementally added to the right side of each previous character. If the caret gets to the right border of the control, the text automatically continues to the next line, although it is still considered as one paragraph. To start a new paragraph, the user has to press Enter. The ability for the text to continue on the next line when the caret encounters the right border of the multi-line text box is controlled by the WordWrap property whose default Boolean value is set to true. If you do not want text to wrap to the subsequent line, set the WordWrap property to false. You can also set it programmatically as follows:

private void button1_Click(object  sender, EventArgs  e)
{
    textBox1.WordWrap = false;
}

Using Scroll Bars

When a text box has been configured to hold multiple lines and once its text becomes too long, part of the content could become hidden. To show the hidden part, the control should be equipped with scrollbars so the user can navigate up and down, left and right. To support the display of scrollbars, the TextBox class is equipped with the ScrollBars property. You can specify the option of this property at either the design time or the run time or both.

The TextBox.ScrollBars property is based on the ScrollBars enumeration that has four members:

methods to Manage a Multi-Line Text Box

The multi-line text box control is based on the TextBox class. To dynamically create a multi-line text box, declare a TextBox variable and use its default constructor to initialize it. The other operations the user can perform on a multi-line text box can be controlled by methods such as Undo(), Cut(), Copy(), Paste(), Clear() or SelectAll() that we reviewed for the text box control and they function the same.

Here are examples: 

private void mnuEditUndo_Click(object  sender, EventArgs  e)
{
	 this.txtNotice.Undo();
}
private void mnuEditCut_Click(object  sender, EventArgs  e)
{
	 this.txtNotice.Cut();
}
private void mnuEditCopy_Click(object  sender, EventArgs  e)
{
	 this.txtNotice.Copy();
}
private void mnuEditPaste_Click(object  sender, EventArgs  e)
{
	 this.txtNotice.Paste();
}

Text-Boxes and Databases

Data Entry With Text Boxes

The text box is the most common and the simplest control used to request a value from a user and giving it to a column of a table. The primary value a user enters in a text box is a string. In most cases, you don't have to perform any special processing: You can just get the value and assign it to a column of a table.

To use the value of a text box and give it to the column of a table, simply get the value from the Text property of the control and pass it in the placeholder of the value of the column. The value must be passed as a string. This means that you must remember to surround it with 'and'. Here is an example:

using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;

public class Exercise : System.Windows.Forms.Form
{
    Label lblEmployeeName;
    TextBox txtEmployeeName;
    Button btnAddEmployee;
    Button btnCreateDatabase;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        btnCreateDatabase = new Button();
        btnCreateDatabase.Text = "Create Database";
        btnCreateDatabase.Location = new Point(12, 12);
        btnCreateDatabase.Width = 120;
        btnCreateDatabase.Click += new EventHandler(btnCreateDatabaseClick);

        btnAddEmployee = new Button();
        btnAddEmployee.Text = "Add Employee";
        btnAddEmployee.Location = new Point(12, 76);
        btnAddEmployee.Width = btnCreateDatabase.Width;
        btnAddEmployee.Click += new EventHandler(btnAddEmployeeClick);

        lblEmployeeName = new Label();
        lblEmployeeName.AutoSize = true;
        lblEmployeeName.Text = "Employee Name:";
        lblEmployeeName.Location = new Point(12, 44);

        txtEmployeeName = new TextBox();
        txtEmployeeName.Location = new Point(120, 44);

        Text = "Database Exercise";
        Controls.Add(lblEmployeeName);
        Controls.Add(txtEmployeeName);
        Controls.Add(btnAddEmployee);
        Controls.Add(btnCreateDatabase);

        StartPosition = FormStartPosition.CenterScreen;
    }

    void btnCreateDatabaseClick(object sender, EventArgs e)
    {
        using (SqlConnection cntExercise =
            new SqlConnection("Data Source='EXPRESSION';" +
                              "Integrated Security='SSPI';"))
        {
            SqlCommand cmdExercise =
                new SqlCommand("IF EXISTS (SELECT name " +
                               "FROM sys.databases WHERE name = N'Exercise1' " +
                               ") " +
                               "DROP DATABASE Exercise1; " +
                               "CREATE DATABASE Exercise1;", cntExercise);

            cntExercise.Open();
            cmdExercise.ExecuteNonQuery();
        }

        using (SqlConnection cntExercise =
            new SqlConnection("Data Source='EXPRESSION'; " +
                              "Database='Exercise1'; " +
                              "Integrated Security='SSPI';"))
        {
            SqlCommand cmdExercise =
                new SqlCommand("CREATE SCHEMA Personnel;",
                               cntExercise);

            cntExercise.Open();
            cmdExercise.ExecuteNonQuery();
        }

        using (SqlConnection cntExercise =
            new SqlConnection("Data Source='EXPRESSION';" +
                              "Database='Exercise1'; " +
                              "Integrated Security='SSPI';"))
        {
            SqlCommand cmdExercise =
                new SqlCommand("CREATE TABLE Personnel.Employees" +
                               "(" +
                               "    EmployeeName nvarchar(50)" +
                               ");",
                               cntExercise);

            cntExercise.Open();
            cmdExercise.ExecuteNonQuery();
        }
    }

    private void btnAddEmployeeClick(object sender, EventArgs e)
    {
        using (SqlConnection cntExercise =
            new SqlConnection("Data Source='EXPRESSION';" +
                              "Database='Exercise1';" +
                              "Integrated Security=SSPI;"))
        {
            SqlCommand cmdExercise =
                new SqlCommand("INSERT INTO Personnel.Employees " +
                               "VALUES(N'" + txtEmployeeName.Text + "');",
                               cntExercise);

            cntExercise.Open();
            cmdExercise.ExecuteNonQuery();
        }
    }
}

public class Program
{
    [STAThread]
    static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

Transact-SQL supports various types of natural numbers in data types such as int, tinyint, smallint, and bigint. Various Windows controls can be used to provide such values. The most common control is the text box, in which the user can simply type the value. To get such a value, you can (optionally, meaning in most cases you don't have to) call the static Parse() method from the appropriate data type and pass it in the placeholder of the value in the INSERT statement. The value is passed without single-quotes. Here is an example:

using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;

public class Exercise : System.Windows.Forms.Form
{
    Label lblEmployeeNumber;
    TextBox txtEmployeeNumber;
    Button btnAddEmployee;
    Button btnCreateDatabase;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        btnCreateDatabase = new Button();
        btnCreateDatabase.Text = "Create Database";
        btnCreateDatabase.Location = new Point(12, 12);
        btnCreateDatabase.Width = 120;
        btnCreateDatabase.Click += new EventHandler(btnCreateDatabaseClick);

        btnAddEmployee = new Button();
        btnAddEmployee.Text = "Add Employee";
        btnAddEmployee.Location = new Point(12, 76);
        btnAddEmployee.Width = btnCreateDatabase.Width;
        btnAddEmployee.Click += new EventHandler(btnAddEmployeeClick);

        lblEmployeeNumber = new Label();
        lblEmployeeNumber.AutoSize = true;
        lblEmployeeNumber.Text = "Employee Number:";
        lblEmployeeNumber.Location = new Point(12, 44);

        txtEmployeeNumber = new TextBox();
        txtEmployeeNumber.Location = new Point(120, 44);

        Text = "Database Exercise";
        Controls.Add(lblEmployeeNumber);
        Controls.Add(txtEmployeeNumber);
        Controls.Add(btnAddEmployee);
        Controls.Add(btnCreateDatabase);

        StartPosition = FormStartPosition.CenterScreen;
    }

    void btnCreateDatabaseClick(object sender, EventArgs e)
    {
        using (SqlConnection cntExercise =
            new SqlConnection("Data Source='EXPRESSION';" +
                              "Integrated Security='SSPI';"))
        {
            SqlCommand cmdExercise =
                new SqlCommand("IF EXISTS (SELECT name " +
                               "FROM sys.databases WHERE name = N'Exercise1' " +
                               ") " +
                               "DROP DATABASE Exercise1; " +
                               "CREATE DATABASE Exercise1;", cntExercise);

            cntExercise.Open();
            cmdExercise.ExecuteNonQuery();
        }

        using (SqlConnection cntExercise =
            new SqlConnection("Data Source='EXPRESSION'; " +
                              "Database='Exercise1'; " +
                              "Integrated Security='SSPI';"))
        {
            SqlCommand cmdExercise =
                new SqlCommand("CREATE SCHEMA Personnel;",
                               cntExercise);

            cntExercise.Open();
            cmdExercise.ExecuteNonQuery();
        }

        using (SqlConnection cntExercise =
            new SqlConnection("Data Source='EXPRESSION';" +
                              "Database='Exercise1'; " +
                              "Integrated Security='SSPI';"))
        {
            SqlCommand cmdExercise =
                new SqlCommand("CREATE TABLE Personnel.Employees" +
                               "(" +
                               "    EmployeeNumber int" +
                               ");",
                               cntExercise);

            cntExercise.Open();
            cmdExercise.ExecuteNonQuery();
        }
    }

    private void btnAddEmployeeClick(object sender, EventArgs e)
    {
        using (SqlConnection cntExercise =
            new SqlConnection("Data Source='EXPRESSION';" +
                              "Database='Exercise1';" +
                              "Integrated Security=SSPI;"))
        {
            SqlCommand cmdExercise =
                new SqlCommand("INSERT INTO Personnel.Employees " +
                               "VALUES(" + int.Parse(txtEmployeeNumber.Text) + ");",
                               cntExercise);

            cntExercise.Open();
            cmdExercise.ExecuteNonQuery();
        }
    }
}

public class Program
{
    [STAThread]
    static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}


Home Copyright © 2014-2020, FunctionX