Learn how to perform basic string operations in a Windows Form using C#.
This tutorial demonstrates the following development tasks:
C# and .NET
- How to perform basic string operations.
- How to use regular expressions with the .NET Regex class.
- How to retrieve the current date and time using the .NET DateTime class.
- Windows Forms naming convention.
- How to control the appearance of text in the controls.
- How to enable and disable controls.
- How to use the Windows Forms MessageBox class.
- How to organize the Windows Forms controls with the .NET GroupBox class.
- Creating a rudimentary help system.
This advanced tutorial is not intended as an introductory C# programming tutorial. You will find links to free C# tutorials and books, as well as the development software in the reference section of my first article in this series, Advanced Introduction to C# with Windows Forms – Part 1.
Building and Running the Project
From the Download section of this tutorial, download the project called Strings. Build and run this application. Enter your first and last name and click Concatenate. Enter a test string and click Perform Ops. Click the Text Color button and change the text color to blue. The following screen shot shows how your application will appear.
Figure 1: Strings Application
C# and .NET Development Concepts
String concatenation is the operation of appending one string to the end of another string. For example, the concatenation of "Hello, " and "World!" is "Hello, World!". You can use the + or += operators to concatenate string variables. The following code illustrates how to use the + operator. In this code example you combine the character string values that you extract from the text box controls with the literal strings to form a complete sentence that you assign to the Text property of the label control labelConcatOutputText.
Figure 2: Concatenation with the + Operator
The following code snippet illustrates how to use the += operator. In this code example you extract the character string value from the text box control textBoxTestString and assign it to the testString variable. You form the output string by combining several string values into one string that you later assign to the Text property of the label control labelStringOpsOutputText.
Figure 3: Concatenation with the += Operator
In order to advance text to the next line in the Windows Forms Label control you can use one of the two new line forms:
- “\r\n" string literal, where “\r" is a carriage return, and “\n" is a new line.
- Environment.NewLine property. Environment.NewLine property returns the newline string defined for your application environment. In Windows environment, the value returned by Environment. NewLine property is the same as the “\r\n" string literal.
Count String Characters
Every object of the type string has a length. As shown in the Figure 3, the expression testString.Length returns the length of the testString string object.
You can also find the length of a string literal using the Length property. For example, the expression "My name is Ben.".Length will return 15.
Count Words in a Character String with Regular Expressions
You can use a regular expression with the .NET Regex class to count the words in a string. As shown in the Figure 3, in the following expression Regex.Matches method searches the testString string for all occurrences specified in the regular expression.
System.Text.RegularExpressions.MatchCollection wordCollection = System.Text.RegularExpressions.Regex.Matches(testString, @"[\S]+");
You can use [\S]+ regular expression to count the words in a string, where square brackets contain the characters to match, \S matches any non-white-space character, and + matches the previous element one or more times.
The Matches method returns the wordCollection collection found by the search. The Count property of the wordCollection collection contains the number of words in a string.
Convert a Character String to Upper/Lower Case
The .NET String class provides many useful methods. This application demonstrates how to use ToUpper and ToLower methods of the String class as illustrated in the Figure 3. The ToUpper method returns a copy of the testString converted to uppercase. The ToLower method returns a copy of the testString converted to lowercase. You can use the ToUpper method to convert a string to uppercase for use in case-insensitive applications.
Retrieve Current Date and Time
Figure 2 shows how to use the .NET DateTime structure that represents an instant in time. You can use the Today property of the DateTime structure to get the current date, and the Now property to get the current time. ToShortDateString and ToShortTimeString methods make it easy to convert the DateTime object values to their string equivalents.
Windows Forms Development Concepts
Change the Text Color in the Windows Forms Controls
In this application, you can use the .NET ColorDialog class to specify the text color for your text box and label controls. The following code illustrates how to use the color value returned by the ColorDialog to set the text color of the text box and label controls.
Figure 4: Choose Text Color for Text Box and Label Controls
Enable and Disable Windows Forms Controls
The .NET Control class defines the base class for all Windows Forms controls with visual representation, such as labels, text boxes and buttons. With the Control class Enabled property, you can enable or disable controls at run time. Because all Windows Forms visual controls inherit this ability from the Control class, by setting the Enabled property, you can enable or disable controls. In the Strings application, you can use the Disable Help button to disable, and the Enable Help to enable the Help buttons using this code:
Figure 5: Enable and Disable Help
Use the Windows Forms MessageBox Class
You can use the .NET MessageBox class as a predefined dialog box to display application-related information to the user. You can also use it to request information from the user. In the Strings application the MessageBox class is used to accomplish the following:
- To ask the user whether or not he intends to close the application. As the following code shows, if the user clicks on the Yes button, the application is closed. If the user clicks on the No button, the application remains open.
Figure 6: Asks the Users to Close the Application
- As the following code shows, when the user clicks on one of the Help buttons, the MessageBox dialog informs the user on how to proceed, hence implementing a very basic help system.
Figure 7: Simple Help System
Organize the Windows Forms Controls with the GroupBox Class
The Strings application holds quite a few controls. You will make these controls easier to use by the function-based grouping. You can use the GroupBox control as a container for other controls, such as labels, text boxes and buttons. The GroupBox control has a border and a header for user interface content.
In the Strings application, you use two GroupBox controls to logically group two collections of controls on a form. As you can see in Figure 1, the controls are divided into two main groups with the following captions: Concatenated Strings and String operations: length, upper, lower, word count.
Further Reading and Reference
- Strings (C# Programming Guide)
- Regex Class
- Regular Expression Language - Quick Reference
- Character literals
- How to Create the Best User Experience for Your Application