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.