Home > Backend Development > C++ > How to Restrict a Windows Forms TextBox to Accept Only Numeric Input?

How to Restrict a Windows Forms TextBox to Accept Only Numeric Input?

Mary-Kate Olsen
Release: 2025-02-01 18:31:09
Original
440 people have browsed it

How to Restrict a Windows Forms TextBox to Accept Only Numeric Input?

Limit the TextBox input in the Windows window application as value

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;
    }
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template