C # use a regular expression in Winform to restrict TextBox to numbers only

Source: Internet
Author: User

Yesterday, I searched the internet, especially the garden, for how to restrict TextBox from entering only numbers under Winform. However, the results are basically implemented using regular expressions in the web environment, but it does not seem to be found on the Winform platform. Follow your own ideas.

First, define a string to represent the regular expression of a number:
Private string pattern = @ "^ [0-9] * $ ";

Then define a string to record the original content of the TextBox, so that when the input is not a number, the content of the text box can be restored to the original value (I don't know how to restore the content of the TextBox to the previous time, I can only use this stupid method ):

Private string param1 = null;

Then, we can judge whether the input is a number in the TextChanged event of textBox. If it is a number, the content of the text box is saved in param1; if it is not a number, cancel this input, that is, reset the text box content to param1: Private void textBoxParam1_TextChanged (object sender, EventArgs e)
{
Match m = Regex. Match (this. textBoxParam1.Text, pattern); // Match the Regular Expression

If (! M. Success) // The input is not a number.
{
This. textBoxParam1.Text = param1; // the textBox content remains unchanged.

// Position the cursor at the end of the text box
This. textBoxParam1.SelectionStart = this. textBoxParam1.Text. Length;
}
Else // enter a number
{
Param1 = this. textBoxParam1.Text; // Save the current textBox Value
}
}

In this way, the regular expression is basically used to limit the input numbers of TextBox.
Similar to other expressions, you only need to set the content of the regular expression to be compared.

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.