Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to set up only digits in TextBox in C #

Shulou Source: shulou.com Published: 2022-06-02 07:37:57 09月21日 Update

It is believed that many inexperienced people are at a loss about how to set up TextBox only to input numbers in C #. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Solution method

The general practice is to handle it in a keystroke event to determine the value of keychar. You can only enter numbers, decimal points, and Backspace,del keys. The keychar for the number 0 is 57, the decimal point is 46, the Backspace is 8, and the decimal point is 46.

When entering a decimal point, the decimal point entered should be in accordance with the format of the number, and things like 9.9.9 cannot be entered. The way to do this is to use float.TryParse to convert the values before and after the Textbox, and then compare the conversion results.

Code implementation

We enter the following code in the KeyPress time in our added textBox control

Private void textBox1_KeyPress (object sender, KeyPressEventArgs e)

{

/ / determine whether the button is the type to be entered.

If (int) e.KeyChar)

< 48 || (int)e.KeyChar >

57) & & (int) e.KeyChar! = 8 & & (int) e.KeyChar! = 46)

E.Handled = true

/ / the treatment of decimal point.

If ((int) e.KeyChar = = 46) / / decimal point

{

If (textBox1.Text.Length

Tags: Inputs decimals decimal points numbers methods codes practices content that is keystrokes more problems processing helplessness for this events causes this skills Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology MySQL OPPO Reno Shulou Information MariaDB