C# Winforms custom TextBox control, limit the length of text

Lionsure 2020-08-10 Original by the website

TextBox treats the length of DBCS and English without any difference in C# winform, that is, two bytes of DBCS are also treated as length 1, which brings trouble to saving data. In order to save space, each field is usually limited in length. If it exceeds the specified length, an exception will be generated. Therefore, the length of character must be accurately determined. Of course, it can also be checked at the time of submission, but if it is used a lot, it is a little troublesome to check every time. It is more convenient to define it as a control, and just pull it into the Form when it is used.

 

C# Winforms custom TextBox control, limit the length of text

1. Right-click the project to be customized for the TextBox control, and select "Add → Class" in turn, as shown in Figure 1:

C# Winforms custom TextBox control, limit the length of text

Figure 1

2. Enter the class file name, such as UserTextBox, and click "Add" to create a class file.

3. Add using System.Windows.Forms;, and then inherit the TextBox class.

4. Override the OnTextChanged method in this class, and then write a code to check the length of the input characters, mainly to distinguish between DBCS and English. One DBCS has a length of 2, and an English letter has a length of 1. The code is as follows:

using System;
       using System.Collections.Generic;
       using System.Text;
       using System.Windows.Forms;

namespace winform
       {
              public class UserTextBox : TextBox
              {
                     protected override void OnTextChanged(EventArgs e)
                     {
                            string inputText = this.Text;
                            int len = ASCIIEncoding.Default.GetByteCount(inputText);
                            int maxLen = this.MaxLength;

                     //Get the binary array of input string
                            byte[] b = ASCIIEncoding.Default.GetBytes(inputText);
                            if (len > maxLen)
                            {
                                   //Convert the intercepted byte array into a string
                                   this.Text = ASCIIEncoding.Default.GetString(b, 0, maxLen);
                                   this.SelectionStart = maxLen;//Position the cursor at the end of input character
                            }
                            base.OnTextChanged(e);
                     }
              }
       }

5. Generate the project, go to the Form interface, you can see the custom control in the toolbox, as shown in Figure 2:

C# custom control

Figure 2

6. To use it there, drag the UserTextBox to the Form or use it to define the textbox object. It is already possible to accurately check the length of DBCS and English.