Home

Windows Controls: The Text Box

 

Introduction to Text Boxes

 

Description

A text box is a Windows control used to get or display text for the user's interaction. 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, 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, in 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.

ApplicationPractical Learning: Introducing Text Boxes

  1. Create a Window Forms Application named ElementaryAddition2
  2. Design the form as follows:
     
    Elementary Addition
    Control Text Name TextAlign Font Additional Properties
    Label 00 lblOperand1 Center Name: Tahoma
    Font Style: Bold
    Size:   48
    AutoSize: True
    ForeColor: Blue
    Label +   Center Name: Arial
    Font Style: Bold
    Size:   48
    AutoSize: True
    ForeColor: Maroon
    Label 00 lblOperand2 Center Name: Tahoma
    Font Style: Bold
    Size:   48
    AutoSize: True
    ForeColor: Blue
    Label =   Center Name: Arial
    Size:   48
    Font Style: Bold
    AutoSize: True
    ForeColor: Green
    TextBox 000 txtResult Center Name: Tahoma
    Font Style: Bold
    Size:   48
     
    Label New Operation lblNewOperation Center Name: Tahoma
    Font Style: Bold
    Size:   48
    AutoSize: True
    BorderStyle: Fixed3D
    ForeColor: White
    BackColor:Maroon 
    Label Check lblCheckAnswer Center Name: Tahoma
    Font Style: Bold
    Size: 28
    AutoSize: True
    BorderStyle: Fixed3D
    ForeColor: White
    BackColor:Maroon 
    Label Quit lblQuit Center Name: Tahoma
    Font Style: Bold
    Size: 28
    AutoSize: True
    BorderStyle: FixedSingle
  3. Double-click the New Operation label and implement its event as follows:
    System::Void lblNewOperation_Click(System::Object^  sender, 
    		  		   System::EventArgs^  e)
    {
        int operand1;
        int operand2;
    
        Random ^ rnd = gcnew Random;
    
        operand1 = rnd->Next(99);
        operand2 = rnd->Next(99);
        int result = operand1 + operand2;
    	
        lblOperand1->Text = operand1.ToString();
        lblOperand2->Text = operand2.ToString();
        txtResult->Text   = "";
        txtResult->Focus();
    }
  4. Return to the form and double-click the Check label
  5. Implement its event as follows:
    System::Void lblCheckAnswer_Click(System::Object^  sender, 
    		  		  System::EventArgs^  e)
    {
        int Operand1 = 0;
        int Operand2 = 0;
        int Result   = 0;
    
        Operand1 = int::Parse(lblOperand1->Text);
        Operand2 = int::Parse(lblOperand2->Text);
            
        Result = int::Parse(txtResult->Text);
    
        if (Result == (Operand1 + Operand2))
                MessageBox::Show("WOW - Good Answer");
        else
                MessageBox::Show("PSSST - Wrong Answer");
    
        lblNewOperation_Click(sender, e);
    }
  6. Return to the form and double-click Quit
  7. Implement its event as follows:
    System::Void lblQuit_Click(System::Object^  sender, System::EventArgs^  e)
    {
        Close();
    }
  8. Execute the application and test it
  9. Click the Close button to close the form and return to your programming environment

Characteristics of Text Boxes

 

Text

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, the Form Designer initializes it with the name of the control; this would be textBox1 for the first text box, textBox2 for the second, etc. If you want the control to display some text when the form launches, type the text in the Text property field in the Properties window. Otherwise, if you want the text box to be empty when it comes up for the first time, delete the content of the Text field.

Beside the Text property, the text box shares many of the characteristics of a label: text alignment, font, color, etc.

ApplicationPractical Learning: Creating Text Boxes

  1. To start a new application, on the main menu, click File -> New Project...
  2. In the middle list, click Windows Application and set the name to PayrollProcessing1
  3. Click OK
  4. Design the form as follows:
     
    Payroll Processing
    Control Name Text Other Properties
    GroupBox GroupBox   Employee Identification  
    Label Label   &Employee Name:  
    TextBox TextBox txtEmployeeName    
    Label Label   Hourly &Salary:  
    TextBox TextBox txtHourlySalary    
    GroupBox GroupBox   Time Values  
    Label Label   Monday  
    Label Label   Tuesday  
    Label Label   Wednesday  
    Label Label   Thursday  
    Label Label   Friday  
    Label Label   Saturday  
    Label Label   Sunday  
    Label Label   First Week:  
    TextBox TextBox txtWeek1Monday 0.00 TextAlign: Right
    TextBox TextBox txtWeek1Tuesday 0.00 TextAlign: Right
    TextBox TextBox txtWeek1Wednesday 0.00 TextAlign: Right
    TextBox TextBox txtWeek1Thursday 0.00 TextAlign: Right
    TextBox TextBox txtWeek1Friday 0.00 TextAlign: Right
    TextBox TextBox txtWeek1Saturday 0.00 TextAlign: Right
    TextBox TextBox txtWeek1Sunday 0.00 TextAlign: Right
    Label Label   Second Week:  
    TextBox TextBox txtWeek2Monday 0.00 TextAlign: Right
    TextBox TextBox txtWeek2Tuesday 0.00 TextAlign: Right
    TextBox TextBox txtWeek2Wednesday 0.00 TextAlign: Right
    TextBox TextBox txtWeek2Thursday 0.00 TextAlign: Right
    TextBox TextBox txtWeek2Friday 0.00 TextAlign: Right
    TextBox TextBox txtWeek2Saturday 0.00 TextAlign: Right
    TextBox TextBox txtWeek2Sunday 0.00 TextAlign: Right
    GroupBox GroupBox   Payroll Processing  
    Label Label   Hours  
    Label Label   Amount  
    Label Label lblCalculate Calculate AutoSize: False
    Label Label   Regular  
    TextBox TextBox txtRegularTime 0.00 TextAlign: Right
    TextBox TextBox txtRegularAmount 0.00 TextAlign: Right
    Label Label   Net Pay:  
    TextBox TextBox txtNetPay 0.00 TextAlign: Right
    Label Label   Overtime  
    TextBox TextBox txtOvertime 0.00 TextAlign: Right
    TextBox TextBox txtOvertimeAmount 0.00 TextAlign: Right
    Label Label btnClose   AutoSize: False

Read-Only

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.

Practical LearningPractical Learning: Setting the Read-Only Attribute

  1. On the form, click the text box at the intersection of Time and Regular
  2. In the Properties window, double-click ReadOnly to change its value to True
  3. Do the same for the following text boxes: TxtRegularAmount, TxtNetPay, TxtOvertime, and TxtOvertimeAmount
 
 
 

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.

ApplicationPractical Learning: Auto-Completing a Text Box

  1. On the form, click the txtEmployeeName text box
  2. In the Properties window, click AutoCompleteCustomSource and click its ellipsis button
  3. In the String Collection Editor, enter the following names:
    Micheline Hammond
    Paul Bertrand Yamaguchi
    Gertrude Monay
    Ernestine Ngaleu
    Andy Barang
    Christophe Yuen
    Jean Michel Kankan
  4. Click OK
  5. Click AutoCompleteSource, then click the arrow of its combo box and select CustomSource
  6. Click AutoCompleteMode, then click the arrow of its combo box and select SuggestAppend
  7. On the form, double-click the Calculate label
  8. Implement its event as follows:
    System::Void lblCalculate_Click(System::Object^ sender, System::EventArgs^ e)
    {
        double monday1 = 0.00, tuesday1 = 0.00, wednesday1 = 0.00,
               thursday1 = 0.00, friday1 = 0.00, saturday1 = 0.00,
               sunday1 = 0.00, monday2 = 0.00, tuesday2 = 0.00,
               wednesday2 = 0.00, thursday2 = 0.00,
        friday2 = 0.00, saturday2 = 0.00, sunday2 = 0.00;
        double totalHoursWeek1, totalHoursWeek2;
    
        double regHours1 = 0.00, regHours2 = 0.00,
               ovtHours1 = 0.00, ovtHours2 = 0.00;
        double regAmount1 = 0.00, regAmount2 = 0.00,
               ovtAmount1 = 0.00, ovtAmount2 = 0.00;
        double regularHours, overtimeHours;
        double regularAmount, overtimeAmount, totalEarnings;
    
        double hourlySalary = 0.00;
    
        // Retrieve the hourly salary
        hourlySalary = double::Parse(txtHourlySalary->Text);
        // Retrieve the value of each day worked
        monday1 = double::Parse(txtWeek1Monday->Text);
        tuesday1 = double::Parse(txtWeek1Tuesday->Text);
        wednesday1 = double::Parse(txtWeek1Wednesday->Text);
        thursday1 = double::Parse(txtWeek1Thursday->Text);
        friday1 = double::Parse(txtWeek1Friday->Text);
        saturday1 = double::Parse(txtWeek1Saturday->Text);
        sunday1 = double::Parse(txtWeek1Sunday->Text);
             
        monday2 = double::Parse(txtWeek2Monday->Text);
        tuesday2 = double::Parse(txtWeek2Tuesday->Text);
        wednesday2 = double::Parse(txtWeek2Wednesday->Text);
        thursday2 = double::Parse(txtWeek2Thursday->Text);
        friday2 = double::Parse(txtWeek2Friday->Text);
        saturday2 = double::Parse(txtWeek2Saturday->Text);
        sunday2 = double::Parse(txtWeek2Sunday->Text);
             
        // Calculate the total number of hours for each week
        totalHoursWeek1 = monday1 + tuesday1 + wednesday1 +
                          thursday1 + friday1 + saturday1 + sunday1;
        totalHoursWeek2 = monday2 + tuesday2 + wednesday2 +
                          thursday2 + friday2 + saturday2 + sunday2;
    
        // The overtime is paid time and half
        double ovtSalary = hourlySalary * 1.5;
    
        // If the employee worked under 40 hours, there is no overtime
             if (totalHoursWeek1 < 40)
             {
                    regHours1 = totalHoursWeek1;
                    regAmount1 = hourlySalary * regHours1;
                    ovtHours1 = 0.00;
                    ovtAmount1 = 0.00;
             } // If the employee worked over 40 hours, calculate the overtime
             else if (totalHoursWeek1 >= 40)
             {
                    regHours1 = 40;
                    regAmount1 = hourlySalary * 40;
                    ovtHours1 = totalHoursWeek1 - 40;
                    ovtAmount1 = ovtHours1 * ovtSalary;
             }
    
            if (totalHoursWeek2 < 40)
            {
                    regHours2 = totalHoursWeek2;
                    regAmount2 = hourlySalary * regHours2;
                    ovtHours2 = 0.00;
                    ovtAmount2 = 0.00;
            }
            else if (totalHoursWeek2 >= 40)
            {
                    regHours2 = 40;
                    regAmount2 = hourlySalary * 40;
                    ovtHours2 = totalHoursWeek2 - 40;
                    ovtAmount2 = ovtHours2 * ovtSalary;
            }
    
            regularHours = regHours1 + regHours2;
            overtimeHours = ovtHours1 + ovtHours2;
            regularAmount = regAmount1 + regAmount2;
            overtimeAmount = ovtAmount1 + ovtAmount2;
            totalEarnings = regularAmount + overtimeAmount;
    
            txtRegularTime->Text = regularHours.ToString("F");
            txtOvertime->Text = overtimeHours.ToString("F");
            txtRegularAmount->Text = regularAmount.ToString("F");
            txtOvertimeAmount->Text = overtimeAmount.ToString("F");
    
            txtNetPay->Text = totalEarnings.ToString("F");
    }
  9. Return to the form and double-click the Close label
  10. Implement it as follows:
    System::Void lblClose_Click(System::Object^  sender, System::EventArgs^  e)
    {
    	Close();
    }
  11. Execute the application to see the result
     
    Payroll Information
  12. Close the form and return to your programming environment

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 them un-readable, you can use the PasswordChar property. Although this property is a char type of data, changing it actually accomplishes two things:

  • If you type a character in its field in the Properties window, for example if you type *, any character typed in it would be un-readable
  • Any character in the control would be replaced by the value of this property. You can use any alphabetic character or digit to represent the characters that would be typed but you must provide only one character.

Methods of Managing a Text Box 

The text box 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.

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();

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. After the starting position, you can specify the number of characters to include in the selection. This is done using the SelectionLength property. 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. 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();

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();
 
 
   
 

Home Copyright © 2004-2010 FunctionX, Inc. Next