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

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

DDD
DDDOriginal
2025-02-01 18:46:101031browse

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

Implement the numerical input verification in the Windows window application

Question:

In the Windows window application, how to configure the text box to accept only the integer value? Ideally, an invalid character input should be ignored or marked immediately.

Solution:

Method 1: Use Numericupdown control

Consider using Numericupdown control, it provides a built -in numerical input filtering function. It also easily uses keyboard arrows to increase and decreases. Method 2: Processing the keyboard incident

For more common solutions, process keyboard events to verify input. The following is an example of the code processing program on the two events on TextBox:

You can customize this code according to specific needs:

If the decimal bit is not allowed, please remove the check of '.'.
<code class="language-c#">private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
        (e.KeyChar != '-')) //允许负数
    {
        e.Handled = true;
    }
}</code>

If the negative value is allowed, please add a check of '-'.

    Set TextBox1.maxLength to limit the number of numbers that allow allowed to be allowed. This prevents the input from being too long.
  • Through the above methods, you can effectively limit the Windows window TextBox control only to receive an integer input and provide a better user experience.

The above is the detailed content of How to Restrict a Windows Forms TextBox to Accept Only Integer Input?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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