Как в текстбокс вводить только цифры c
Перейти к содержимому

Как в текстбокс вводить только цифры c

  • автор:

How to allow only numbers inside a textbox in Winforms C#

Carlos Delgado

Learn how to prevent the input from non numeric characters inside a textbox in Winforms.

To create an input element on your Windows Form that only accepts numbers, you have 2 options:

A. Use a NumericUpDown control

If you want to create an input that only accepts number, the first thing that you need to think in is the NumericUpDown control. This controls represents a Windows spin box (also known as an up-down control) that displays exclusively numeric values.

You can simply drag and drop this control from your Toolbox in the All Windows Forms components:

NumericUpDown Control Winforms

Or you can add it dinamically using code:

To retrieve its value you can simply access the Value attribute of the control, for example:

Note that the value is returned in decimal type, so you can format it into an integer, string or whatever you need. This field by itself doesn’t allow non-numeric characters inside.

B. With a real textbox

In case you aren’t able to use a NumericUpDown control for some reason, like the usage of a UI framework that only offers a textbox, you can still filter the input by handling properly its KeyPress event. The first you need to do is to add a function to the KeyPress event of your input by adding automatically the event with Visual Studio selecting your textbox and in the Properties toolbox (right bottom corner of VS), then selecting the events tab and double clicking the KeyPress option:

Double Click KeyPress Event Textbox

This will automatically add the KeyPress function on your class that will be empty, then you need to modify it with the following code to prevent the input from non-numeric characters:

To retrieve its value, you would need only to convert the string to a number by using the desired type:

Справочник по C#

Если вы столкнулись с проблемой и хотите поделиться своим опытом, знаниями или у вас есть интересная статья с иностранного сайта, предложение новой темы, статью которую Вы хотите видеть в ближайшем будущем, расскажите нам об этом и мы обязательно поделимся этими знаниями со всеми. Возможно, для других ваши знания, опыт и советы окажутся очень ценными и помогут вовремя найти правильный выход или не совершить ошибок.
Так же если у вас есть предложение о сотрудничестве, пожелания, указать на нарушения сайта или просто сказать слова благодарности, все это вы можете сделать через форму обратной связи. Читать дальше

C# Make a Textbox That Only Accepts Numbers

C# Make a Textbox That Only Accepts Numbers

While making Windows Forms , some text fields only need a numeric value. For example, if we want to get the phone numbers from users then we will have to restrict our textbox to numeric values only.

Please enable JavaScript

In this article, we will focus on the methods that make a textbox that only accepts numbers.

Make a Textbox That Only Accepts Numbers Using KeyPressEventArgs Class in C#

KeyPressEventArgs is a C# class that specifies the character entered when a user presses a key. Its KeyChar property returns the character that the user typed. Here we have used the KeyPress event to limit our textbox to numeric values only.

The key code that performs this action is as follows:

Here e is a KeyPressEventArgs object that uses KeyChar property to fetch the entered key.

Make a Textbox That Only Accepts Numbers Using Regex.IsMatch() Method in C#

In C# we can use regular expressions to check various patterns. A regular expression is a specific pattern to perform a specific action. RegularExpressions is a C# class that contains the definition for Regex.IsMatch() method. In C#, we have ^[0-9]+$ and ^\d+$ regular expressions to check if a string is a number.

The correct syntax to use this method is as follows:

Make a Textbox That Only Accepts Numbers Using NumericUpDown Method

NumericUpDown provides the user with an interface to enter a numeric value using up and down buttons given with the textbox . You can simply drag and drop a NumericUpDown from the Toolbox to create a textbox that only accepts numbers .

You can also create a NumericUpDown object dynamically. The code to generate a NumericUpDown is as follows:

It has several properties which you can modify by opening the Properties Windows .

Программирование на C, C# и Java

Уроки программирования, алгоритмы, статьи, исходники, примеры программ и полезные советы

ОСТОРОЖНО МОШЕННИКИ! В последнее время в социальных сетях участились случаи предложения помощи в написании программ от лиц, прикрывающихся сайтом vscode.ru. Мы никогда не пишем первыми и не размещаем никакие материалы в посторонних группах ВК. Для связи с нами используйте исключительно эти контакты: vscoderu@yandex.ru, https://vk.com/vscode

Ввод в TextBox только цифр и необходимых символов C#

Здравствуйте, очень часто начинающие программисты задают вопрос, как вводить в TextBox только цифры или другие необходимые им символы, игнорируя все остальные. В этой статье мы рассмотрим несколько самых простых и полезных способ решения этой проблемы.

Для этого мы создадим тестовый проект для наглядного примера с одним лишь текстбоксом, у нас он вот такой:

Ввод в TextBox только цифр и необходимых символов C#

Перво-наперво нам необходимо найти событие, благодаря которому сможем отследить нажатие определенных клавиш. Таким событием является KeyPress. Оно будет происходить всегда, когда пользователь нажимает на любую кнопку на клавиатуре. Чтобы перейти к нему, надо для начала выделить TextBox, один раз щёлкнув на него левой кнопкой мыши.

Ввод в TextBox только цифр и необходимых символов C#

Затем следует найти в правой стороне рабочей области Visual Studio окно «Свойства» и перейти в нём на вкладку событий (значок в виде молнии):

Ввод в TextBox только цифр и необходимых символов C#

Примечание: если вы не нашли «Свойства», то просто кликните правой кнопкой мыши по текстбоксу и выберете в появившемся меню соответствующую вкладку.

Далее мы ищем событие KeyPress и дважды нажимаем на него левой кнопкой мыши. Нас перенесет к коду этого события. Далее мы рассмотрим несколько вариантов решения проблемы с вводом определенных символов в TextBox. Сначала будут идти варианты только с выводом цифр, а затем и другие (с Backspace, пробелом, запятой и проч.)

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *