A solution to the control of input characters in a TextBox

Source: Internet
Author: User
Solution | Control we know that in C #, TextBox controls have KeyPress, KeyUp, and KeyDown events to control the input characters, but as you can see, these events have a certain flaw in the control of the input characters, if you use the Chinese input method, So many of the characters you don't want to enter can also be entered. These days to do the procedure, this problem, my solution is very simple, since these three events no longer work, then I use the TextBox control in the moment can occur textchanged events, in order to expect to do something in this event, to achieve the purpose of controlling characters. Nonsense is not much to say, I will control the input characters for the number of code paste out, I hope everyone to correct, if it can be beneficial to you, I will be more happy.


Private System.Windows.Forms.TextBox TextBox1;
private string text;
Public Form1 ()
{
Text = TextBox1.Text;
}
private void textBox1_TextChanged (object sender, System.EventArgs e)
{
int len = text. Length;
if (Len < textBox1.Text.Length)
{
int index = TEXTBOX1.TEXT.INDEXOF (Text);
char C = (TextBox1.Text.Remove (index,text). Length)) [0];
if (C.compareto (' 0 ') < 0| |c.compareto (' 9 ') >0)
{
TextBox1.Text = Text;
Textbox1.selectionstart = text. Length;
}
}
Text = TextBox1.Text;

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.