In the Windows window application, the user input limit of the text box is often required to be limited to a specific format, such as value. This article discusses two methods to implement this verification:
<.> 1. Use Numericupdown control
Numericupdown control is specially used for numerical input. It will automatically filter out non -digital characters, provide a user -friendly interface, and has a built -in incremental and reduction button.
<.> 2. Processing keyboard events
or, you can handle keyboard events to prevent input non -digital characters. By rewriting the keypress event, a custom filtering mechanism can be achieved. The following is a C# code fragment that demonstrates this method:
This code allows numerical input, including a decimal number with a decimal point. You can add other inspections to limit the number or allow negative values.
By implementing any of these two methods, you can effectively limit the text box to only accept digital input, and provide users with clearer and more efficient data verification experience.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { // 阻止非数字字符和无效的小数点用法 if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.')) { e.Handled = true; } // 只允许一个小数点 if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1)) { e.Handled = true; } }
The above is the detailed content of How to Restrict a Windows Forms TextBox to Accept Only Numeric Input?. For more information, please follow other related articles on the PHP Chinese website!