Ввод числа windows forms c

Here is a simple standalone Winforms custom control, derived from the standard TextBox, that allows only System.Int32 input (it could be easily adapted for other types such as System.Int64, etc.). It supports copy/paste operations and negative numbers:

public class Int32TextBox : TextBox
{
    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        base.OnKeyPress(e);

        NumberFormatInfo fi = CultureInfo.CurrentCulture.NumberFormat;

        string c = e.KeyChar.ToString();
        if (char.IsDigit(c, 0))
            return;

        if ((SelectionStart == 0) && (c.Equals(fi.NegativeSign)))
            return;

        // copy/paste
        if ((((int)e.KeyChar == 22) || ((int)e.KeyChar == 3))
            && ((ModifierKeys & Keys.Control) == Keys.Control))
            return;

        if (e.KeyChar == '\b')
            return;

        e.Handled = true;
    }

    protected override void WndProc(ref System.Windows.Forms.Message m)
    {
        const int WM_PASTE = 0x0302;
        if (m.Msg == WM_PASTE)
        {
            string text = Clipboard.GetText();
            if (string.IsNullOrEmpty(text))
                return;

            if ((text.IndexOf('+') >= 0) && (SelectionStart != 0))
                return;

            int i;
            if (!int.TryParse(text, out i)) // change this for other integer types
                return;

            if ((i < 0) && (SelectionStart != 0))
                return;
        }
        base.WndProc(ref m);
    }

Update 2017: My first answer has some issues:

  • you can type something that’s longer than an integer of a given type (for example 2147483648 is greater than Int32.MaxValue);
  • more generally, there’s no real validation of the result of what has been typed;
  • it only handles int32, you’ll have to write specific TextBox derivated control for each type (Int64, etc.)

So I came up with another version that’s more generic, that still supports copy/paste, + and — sign, etc.

public class ValidatingTextBox : TextBox
{
    private string _validText;
    private int _selectionStart;
    private int _selectionEnd;
    private bool _dontProcessMessages;

    public event EventHandler<TextValidatingEventArgs> TextValidating;

    protected virtual void OnTextValidating(object sender, TextValidatingEventArgs e) => TextValidating?.Invoke(sender, e);

    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        if (_dontProcessMessages)
            return;

        const int WM_KEYDOWN = 0x100;
        const int WM_ENTERIDLE = 0x121;
        const int VK_DELETE = 0x2e;

        bool delete = m.Msg == WM_KEYDOWN && (int)m.WParam == VK_DELETE;
        if ((m.Msg == WM_KEYDOWN && !delete) || m.Msg == WM_ENTERIDLE)
        {
            DontProcessMessage(() =>
            {
                _validText = Text;
                _selectionStart = SelectionStart;
                _selectionEnd = SelectionLength;
            });
        }

        const int WM_CHAR = 0x102;
        const int WM_PASTE = 0x302;
        if (m.Msg == WM_CHAR || m.Msg == WM_PASTE || delete)
        {
            string newText = null;
            DontProcessMessage(() =>
            {
                newText = Text;
            });

            var e = new TextValidatingEventArgs(newText);
            OnTextValidating(this, e);
            if (e.Cancel)
            {
                DontProcessMessage(() =>
                {
                    Text = _validText;
                    SelectionStart = _selectionStart;
                    SelectionLength = _selectionEnd;
                });
            }
        }
    }

    private void DontProcessMessage(Action action)
    {
        _dontProcessMessages = true;
        try
        {
            action();
        }
        finally
        {
            _dontProcessMessages = false;
        }
    }
}

public class TextValidatingEventArgs : CancelEventArgs
{
    public TextValidatingEventArgs(string newText) => NewText = newText;
    public string NewText { get; }
}

For Int32, you can either derive from it, like this:

public class Int32TextBox : ValidatingTextBox
{
    protected override void OnTextValidating(object sender, TextValidatingEventArgs e)
    {
        e.Cancel = !int.TryParse(e.NewText, out int i);
    }
}

or w/o derivation, use the new TextValidating event like this:

var vtb = new ValidatingTextBox();
...
vtb.TextValidating += (sender, e) => e.Cancel = !int.TryParse(e.NewText, out int i);

but what’s nice is it works with any string, and any validation routine.

Here is a simple standalone Winforms custom control, derived from the standard TextBox, that allows only System.Int32 input (it could be easily adapted for other types such as System.Int64, etc.). It supports copy/paste operations and negative numbers:

public class Int32TextBox : TextBox
{
    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        base.OnKeyPress(e);

        NumberFormatInfo fi = CultureInfo.CurrentCulture.NumberFormat;

        string c = e.KeyChar.ToString();
        if (char.IsDigit(c, 0))
            return;

        if ((SelectionStart == 0) && (c.Equals(fi.NegativeSign)))
            return;

        // copy/paste
        if ((((int)e.KeyChar == 22) || ((int)e.KeyChar == 3))
            && ((ModifierKeys & Keys.Control) == Keys.Control))
            return;

        if (e.KeyChar == '\b')
            return;

        e.Handled = true;
    }

    protected override void WndProc(ref System.Windows.Forms.Message m)
    {
        const int WM_PASTE = 0x0302;
        if (m.Msg == WM_PASTE)
        {
            string text = Clipboard.GetText();
            if (string.IsNullOrEmpty(text))
                return;

            if ((text.IndexOf('+') >= 0) && (SelectionStart != 0))
                return;

            int i;
            if (!int.TryParse(text, out i)) // change this for other integer types
                return;

            if ((i < 0) && (SelectionStart != 0))
                return;
        }
        base.WndProc(ref m);
    }

Update 2017: My first answer has some issues:

  • you can type something that’s longer than an integer of a given type (for example 2147483648 is greater than Int32.MaxValue);
  • more generally, there’s no real validation of the result of what has been typed;
  • it only handles int32, you’ll have to write specific TextBox derivated control for each type (Int64, etc.)

So I came up with another version that’s more generic, that still supports copy/paste, + and — sign, etc.

public class ValidatingTextBox : TextBox
{
    private string _validText;
    private int _selectionStart;
    private int _selectionEnd;
    private bool _dontProcessMessages;

    public event EventHandler<TextValidatingEventArgs> TextValidating;

    protected virtual void OnTextValidating(object sender, TextValidatingEventArgs e) => TextValidating?.Invoke(sender, e);

    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        if (_dontProcessMessages)
            return;

        const int WM_KEYDOWN = 0x100;
        const int WM_ENTERIDLE = 0x121;
        const int VK_DELETE = 0x2e;

        bool delete = m.Msg == WM_KEYDOWN && (int)m.WParam == VK_DELETE;
        if ((m.Msg == WM_KEYDOWN && !delete) || m.Msg == WM_ENTERIDLE)
        {
            DontProcessMessage(() =>
            {
                _validText = Text;
                _selectionStart = SelectionStart;
                _selectionEnd = SelectionLength;
            });
        }

        const int WM_CHAR = 0x102;
        const int WM_PASTE = 0x302;
        if (m.Msg == WM_CHAR || m.Msg == WM_PASTE || delete)
        {
            string newText = null;
            DontProcessMessage(() =>
            {
                newText = Text;
            });

            var e = new TextValidatingEventArgs(newText);
            OnTextValidating(this, e);
            if (e.Cancel)
            {
                DontProcessMessage(() =>
                {
                    Text = _validText;
                    SelectionStart = _selectionStart;
                    SelectionLength = _selectionEnd;
                });
            }
        }
    }

    private void DontProcessMessage(Action action)
    {
        _dontProcessMessages = true;
        try
        {
            action();
        }
        finally
        {
            _dontProcessMessages = false;
        }
    }
}

public class TextValidatingEventArgs : CancelEventArgs
{
    public TextValidatingEventArgs(string newText) => NewText = newText;
    public string NewText { get; }
}

For Int32, you can either derive from it, like this:

public class Int32TextBox : ValidatingTextBox
{
    protected override void OnTextValidating(object sender, TextValidatingEventArgs e)
    {
        e.Cancel = !int.TryParse(e.NewText, out int i);
    }
}

or w/o derivation, use the new TextValidating event like this:

var vtb = new ValidatingTextBox();
...
vtb.TextValidating += (sender, e) => e.Cancel = !int.TryParse(e.NewText, out int i);

but what’s nice is it works with any string, and any validation routine.

In this article we are going to create a numeric TextBox in C#.

Numeric TextBox in C# GitHub Link: DevInDeep/NumericTextBox (github.com)

What is Numeric TextBox?

Numeric TextBox is a more advanced version of the classic TextBox control. The main difference, is that it allows the user to enter values in a specific format. Such as: numeric, currency or percent. It should also support displaying values with custom units.

Well, it seems like we already have such control. Numeric Up/Down control allows the user to enter a predefined set of numbers. You can enter a number by using the Up/Down arrows. Or, simply typing the decimal value into the text field itself.

But, sometimes this is not enough. A real numeric TextBox control may come handy in a lot of situations. Entering currencies with specific format for example. A currency would consist of a decimal number prefixed with the currency sign. For example: $49.99. This is not possible with a Numeric Up/Down control.

Here is another example from the metric system: 170cm. This is the height of a person measured in centimeters. What if we want a control that can accept numbers followed by the measurement unit. As we stand right now, it seems like the Numeric Up/Down control is too limited in accepting only numbers. And, on the other hand, the TextBox is too general. It can accept all kinds of input.

What we actually need is a very specific control that can accept a limited user input. And, what’s more we need this control to be reusable, just like the TextBox. In this tutorial we are going to complete this task. We are going to create a Numeric TextBox control in C#.

Create Numeric TextBox Control in C#

More DevInDeep Tutorials:

  • How to Create AutoComplete TextBox in C#
  • Learn how to Send Keys to Another Application in C#
  • Create a true Transparent Image in C#
  • How to Create Rounded Controls in C#

First, let’s create a brand new Windows Forms App project. The language of choice should be set to C#. We are not going over the basic steps of creating a new project, because I assume you already know how to do that. So, we will dive right into the coding part.

Now, add a new C# class to your project and name it: NumericTextBox. Please note that this will be the name of the control as well. In the next section is the complete code listing for the Numeric TextBox.

public class NumericTextBox : TextBox
{
     public NumericTextBox()
     {
          this.KeyPress += NumericTextBox_KeyPress;
     }

     private void NumericTextBox_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;
          }
     }
}

First, let’s go over the inheritance part. In the beginning of this tutorial we mentioned why we can’t use TextBox control. It was too broad- too general for what we were looking for. But, it doesn’t mean that it is the wrong control. It is the right one, but we need to make it accept a more specific set of characters.

As a result, I decided to inherit from TextBox control. It has everything we need. It allows the user to enter an input. Now, we only need to write a C# code that will limit the user in what they are entering. If we want to accept integer and decimal numbers we need to change the default behavior of the control a little bit.

Numeric TextBox Comparison
Numeric UpDown vs Numeric TextBox

KeyPress Event Handler

In the constructor you can see that I am subscribing to the KeyPress event handler. It occurs when a character, space or backspace key is pressed, while the control is in focus. This event, when fired is accompanied with a KeyPressEventArgs object. This object provides data for the KeyPress event. It has two very important properties:

Handled Gets or sets a value indicating whether the KeyPress event was handled.
KeyChar Gets or sets the character corresponding to the key pressed.

Use the KeyChar property to sample keystrokes at run time and to consume or modify a subset of common keystrokes. In other words, this means that whenever a key is pressed, that particular character is stored in the KeyChar property. And, if everything is handled correctly, the character will appear in the TextBox, after the execution of this event.

The KeyPress event also allows us to decide if we want a certain character to appear in our custom Numeric TextBox. If we decide that a certain character is invalid, we can simply set the Handled property to True, and the TextBox won’t display it. And, that is why we decided to handle this event.

There are other events as well, such as: KeyDown and KeyUp. But, they do not offer the possibility of removing a character that doesn’t belong. In case you are interested, here is the order of how these events are fired, when a user presses a key:

  1. Key Down
  2. Key Press
  3. Key Up

Now, let’s take a deep dive into the rest of our C# code.

Code a TextBox that accepts only numeric values

Since, we already know how KeyPress event works, let’s dig deeper into the rest of the code.

if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
{
     e.Handled = true;
}

We saw earlier that, when a user presses a key, the KeyPress event will fire. As a result, a KeyPressEventArgs object is passed, in order to provide additional information. We need this object to process the key the user has pressed. As you can already imagine, we will use the KeyChar property.

Because our goal is to create a Numeric TextBox in C#, we need to set up some conditions. These conditional statements will decide whether or not a character the user has pressed will be accepted. Let’s elaborate the first If statement we are using.

First, we start with the IsControl method. It indicates whether a specified Unicode character is categorized as a control character (for example Backspace). After that we use IsDigit to check if a Unicode character is categorized as a decimal digit. At the end, we check if the character is a dot.

The important thing to note here is that all these conditions have negation next to them. Which means that we check if the key is not a control character and it is not a digit and it is not a dot sign. In a scenario like this we don’t want the TextBox control to show the character. That is why we set the Handled property to true.

TextBox that accepts numeric value with one decimal point

What we actually want is the very opposite of this scenario. We want to have a numeric value with one dot – which is optional. Correspondingly, the custom numeric TextBox will accept integer and a single decimal point numbers.

if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
     e.Handled = true;
}

The second code segment focuses on the dot character. First, we check if the user has entered the dot. Then we check if there already is another dot inside the numeric value. If indeed there is another one, the result of the IndexOf method will be different than -1. It will be 0 or greater. That indicates that the dot character is found at a certain position in the string. And the result this function produces tells us at which position this character appears.

This scenario is not something we want to happen. So, we make sure to set the Handled property to true. This way, the additional dot the user has entered won’t appear in the TextBox control.

If you want to know more about the IndexOf method exposed via the String class, you can read about it here. But the main thing you need to remember is the following definition:

Reports the zero-based index of the first occurrence of a specified Unicode character or string within this instance. The method returns -1 if the character or string is not found in this instance.

Microsoft Documentation

Numeric TextBox in C#, an alternative solution

If you want to create a numeric TextBox in C#, there are quite a few alternative solutions. Let’s review the C# code for something very simple, yet very effective. Here is the C# code listing:

private void NumericTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
     if (!decimal.TryParse((sender as TextBox).Text+e.KeyChar, out decimal number))
          e.Handled = true;
}

As you can already see, we are once again handling the KeyPress event handler. But, this time we are handling it a little bit differently. This is a much simpler solution to the one we already presented above. It consists of only two C# statements.

The foundation for this code segment is the parsing part. You already know that you can parse strings in C# into different types. And we are going to use that to our advantage. We already stated our goal. Create a TextBox control that can only accept numeric values with a single decimal point. So, does this reminds of any particular type? If so, then let’s use it.

First, we will try to parse the string that is already inside the TextBox control. If the string can be parsed into a decimal type, then we can show the character a user has entered. But, if not, then we will simply omit it. As a result, we will get a Numeric TextBox control.

String Casting in C#

We already know that the Text property of a TextBox control, exposes the string, a user has already entered. In our case, we need to pick that string up, and try parse it into a decimal value. To do that we use the TryParse method. This is the definition offered by Microsoft:

Converts the string representation of a number to its Decimal equivalent. A return value indicates whether the conversion succeeded or failed.

Microsoft Documentation

This tells us that the method accepts a string and returns a bool value. The string we are passing is the one contained in the TextBox control. But, like we said earlier we decide which character will appear in the TextBox after the KeyPress event. So, we need to concatenate what we have currently in the TextBox with the currently pressed key.

If the TryParse function returns false, it means that the currently entered character combined with the Text property of the TextBox control is impossible to convert to a decimal number. On the other hand, if it returns true it means the string can be converted to a valid number and the currently pressed key can appear in the TextBox.

You can find more parsing examples here.

Numeric TextBox in C# using Regex

You have many different options when it comes to creating this control. Let’s go over one more. But, this time we are going to be using Regex. Because, it will allow us to validate the user input. For this example to work, I do assume that you have basic understanding of Regex. But, even if you do not, you can simply take over my solution as is.

Let’s look at the C# code listing:

private void NumericTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
     if (!Regex.IsMatch((sender as TextBox).Text + e.KeyChar, @"^[1-9]\d*[.]?(\d+)?$"))
          e.Handled = true;
}

There are many ways how we can restructure this C# code to be more readable. But, for the purposes of this tutorial it is good enough.

Again, we are handling the KeyPress event. Inside we are concatenating the Text property of the control with the newly entered character (that is available inside the KeyChar property). Then, we will evaluate the result string via the IsMatch regex function.

If we look at the Microsoft documentation, we can conclude that this method will return true, only if the Regex engine finds a match in the input string. And, as you can see, we are matching for a decimal numeric value with one, or zero dot characters.

But, we set the Handled property to true, only if the Regex engine doesn’t match the pattern to the input string. As a result, we have another way of creating a Numeric TextBox in C# using Regex.

Numeric TextBox using Regex

Numeric TextBox using Regex pattern matching

Conclusion

You are free to choose any of these approaches. All of them are capable of limiting a TextBox to accept only decimal numbers. But the point to this tutorial goes beyond creating a Numeric TextBox in C#. It shows you how to handle user input, and how to limit and confine a control to accept only certain characters.

Now, it’s your turn. You can create a control that accepts a person’s height in centimeters. Or, you can create a control that accepts a currency numeric combined with the currency type as well. Try and experiment to see what everything is possible by handling the KeyPress event.

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

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

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

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

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

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

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

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

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

Использование в TextBox только цифр.

Способ первый — самый быстрый.

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

char number = e.KeyChar;

if (!Char.IsDigit(number))

{

    e.Handled = true;

}

Вот и всё решение нашей проблемы! Теперь если запустить проект и попробовать что-нибудь написать в нашем TextBox’e, то в него не попадёт ни один другой символ кроме цифр.

Так что же мы тут сделали?

В самой первой строке мы объявили символьную переменную, назвав её number.Благодаря параметру e.KeyChar программа заносит в нашу переменную символ введенной клавиши. Нажали на клавишу «+», в переменную запишется «+», нажали на клавишу «в», в переменную запишется «в» и т.д.

Далее идёт условие !Char.IsDigit(number), которое можно словесно интерпретировать как «если символ из переменной number не относится к категории десятичных цифр» (а нам как раз такие и нужны). А вывод из условия e.Handled = true интерпретируется как «тогда не обрабатывать введенный символ (и, следовательно, не выводить его в TextBox). Иными словами, мы проверяем, является ли любой символ, введенный пользователем десятичной цифрой. Если нет — отбрасываем его, если является — обрабатываем и выводим в TextBox. Легко, просто, быстро!

Способ второй — с кодировкой ASCII.

Однако далеко не всегда можно обойтись только способом, описанным выше. Нам в TextBox’e могут понадобиться и другие символы и клавиши, например, клавиша удаления Backspace, запятая или пробел. В таком случае нам придётся пользоваться помощью таблицей ASCII-кодов. Это совсем несложно. Но для начала разберемся,что вообще такое ASCII.

ASCII — это специальная кодировка, которая присваивает всем используемым в компьютере символам соответствующий числовой код.

Таблицу большинства ASCII-кодов можно просмотреть ниже (кликабельно).

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

Теперь попробуем написать аналогичный код для вывода только цифр используя коды ASCII. Итак, ищем в таблице, под какими номерами расположены наши цифры. Видимо, что нам необходимы коды с 48 по 57 — цифры от 0 до 9. Значит наш код в событии KeyPress будет таким:

char number = e.KeyChar;

if (e.KeyChar <= 47 || e.KeyChar >= 58)

{

    e.Handled = true;

}

Интерпретировать его можно так: «если ASCII-код записанного в переменную number символа будет меньше или равен 47 (все символы в кодировке до цифры «0») или больше или равен 58 (все символы в кодировке после цифры «9»), то не обрабатывать такие символы. При этом оставшиеся символы (как раз все наши цифры)  не будут подходить под этот фильтр и поэтому выведутся в TextBox’e.

Ниже приведены коды с различными фильтрациями клавиш и символов, не ограничивающихся только лишь одними цифрами.

Использование в TextBox цифр и клавиши Backspace.

Код, приведенный ниже, дает возможность использовать в TextBox’e не только цифры, но и клавишу удаления Backspace. В нашем варианте мы смешали оба описанных выше способа, но также можно использовать и только второй способ.

char number = e.KeyChar;

if (!Char.IsDigit(number) && number != 8) // цифры и клавиша BackSpace

{

    e.Handled = true;

}

 Использование в TextBox цифр, запятой и клавиши Backspace.

Если нам потребуется вводить десятичные дроби, то для этой цели понадобится ещё и запятая. Приведем пример кода, на этот раз основанного на ASCII кодировке:

char number = e.KeyChar;

if ((e.KeyChar <= 47 || e.KeyChar >= 58) && number != 8 && number != 44) //цифры, клавиша BackSpace и запятая а ASCII

{

     e.Handled = true;

}

Альтернативный вариант:

char number = e.KeyChar;

if (!Char.IsDigit(number) && number != 8 && number != 44) // цифры, клавиша BackSpace и запятая

{

    e.Handled = true;

}

Использование в TextBox цифр, запятой, основных математических знаков и клавиши Backspace.

Если есть необходимость в создании, например, калькулятора, то может потребоваться отфильтровать не только цифры, но и некоторые другие математически знаки. Пример кода со знаками умножения, деления, сложения и вычитания, а также со скобками можно увидеть ниже:

char number = e.KeyChar;

if ((e.KeyChar <= 47 || e.KeyChar >= 58) && number != 8 && (e.KeyChar <= 39 || e.KeyChar >= 46) && number != 47 && number != 61) //калькулятор

{

    e.Handled = true;

}

Сравнив использованные числовые коды с таблицей ASCII можно легко понять, какой символ соответствует каждому коду.

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

Вот и всё! Мы рассмотрели самые простые способы ввода в TextBox одних цифр или других необходимых символов на языке C#.

Можно скачать исходный код программы, приведенной в статье со всеми перечисленными вариантами использования.

Скачать исходник

В скором времени мы разберем, как можно создавать вывод в TextBox только букв английского и русского алфавитов, а также знаков препинания. Удачного программирования!

0 / 0 / 0

Регистрация: 26.11.2008

Сообщений: 10

1

05.06.2009, 18:31. Показов 23404. Ответов 22


Студворк — интернет-сервис помощи студентам

Здравствуйте.
Помогите реализовать ввод в textBox только чисел.



0



Veyron

107 / 107 / 9

Регистрация: 02.06.2009

Сообщений: 578

05.06.2009, 18:42

2

C#
1
2
3
4
5
6
7
8
9
string input=textBox1.Text;
try
{
 int chislo=Convert.ToInt32(input);
}
catch
{
MessageBox.Show("Введено не число!", "Ошибка!");
}

Если преобразовать можно, то значению chislo присвоется введенное в текстбокс. Иначе отобразится сообщение об ошибке. Можно написать

C#
1
catch{}

Тогда при ошибке ничего вылезать не будет



2



MCSD: APP BUILDER

8794 / 1073 / 104

Регистрация: 17.06.2006

Сообщений: 12,602

05.06.2009, 18:58

3

гоогле «c# textbox только цифры»



0



MAcK

Комбайнёр

1606 / 704 / 77

Регистрация: 27.05.2008

Сообщений: 2,535

05.06.2009, 19:17

4

В общем это уже обсуждалось как это делать!

C#
1
2
3
4
5
6
7
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar))
            {
                e.KeyChar = '\0';
            }
        }



0



Стасёнок

274 / 200 / 33

Регистрация: 18.04.2009

Сообщений: 177

06.06.2009, 03:23

5

А можно и так, в событии textBox1_KeyPress()

C#
1
2
3
4
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), @"[0,1,2,3,4,5,6,7,8,9,\b]");
        }



0



0 / 0 / 0

Регистрация: 26.11.2008

Сообщений: 10

07.06.2009, 01:43

 [ТС]

6

Всем спасибо.



0



Konctantin

969 / 772 / 171

Регистрация: 12.04.2009

Сообщений: 1,700

07.06.2009, 04:37

7

а изврат хотите:

C#
1
2
3
4
5
6
7
8
9
10
private void test_KeyPress(object sender, KeyPressEventArgs e)
{
    if (((TextBox)sender).Text.Contains('-'))
    {
        if (!((Char.IsDigit(e.KeyChar) && ((TextBox)sender).SelectionStart > 0) || e.KeyChar == (char)Keys.Back))
            e.Handled = true;
    }
        else if (!(Char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back || (e.KeyChar == '-' && ((TextBox)sender).SelectionStart == 0)))
            e.Handled = true;
}

Так можно ввести и минусовое число, тоесть можно поставить знак минус, всего один раз и только в начале.



0



Комбайнёр

1606 / 704 / 77

Регистрация: 27.05.2008

Сообщений: 2,535

17.06.2009, 08:59

8

это не изврат, а то что надо !



0



1923 / 428 / 41

Регистрация: 12.07.2007

Сообщений: 2,062

18.06.2009, 02:23

9

А контрол NumericUpDown не подойдет?



0



308 / 161 / 11

Регистрация: 07.06.2009

Сообщений: 538

18.06.2009, 02:37

10

а мне не нравится этот стандартный NumericUpDown — в нем фиксировано колво цифр после запятой, я свой себе делал с поддержкой IDataGridViewEditingControl.



0



969 / 772 / 171

Регистрация: 12.04.2009

Сообщений: 1,700

18.06.2009, 02:39

11

Скорее всего нет, так как там нет контроля по вводу ««, его можно ввести неограниченное количество раз и в любом месте, далее «.» не вводиться.
Тоесть его всеравно надо дорабатывать.
Странно, что в такой среде и нет такого контрола или свойства, которое позволяло бы вводить только цыфры.



0



Комбайнёр

1606 / 704 / 77

Регистрация: 27.05.2008

Сообщений: 2,535

18.06.2009, 14:35

12

NumericUpDown



0



z00m

0 / 0 / 0

Регистрация: 03.07.2009

Сообщений: 5

04.07.2009, 14:48

13

Цитата
Сообщение от IT-Skyline
Посмотреть сообщение

C#
1
2
3
4
5
6
7
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar))
            {
                e.KeyChar = '\0';
            }
        }

А для С++ как реализовать эту возможность?



0



Стасёнок

274 / 200 / 33

Регистрация: 18.04.2009

Сообщений: 177

04.07.2009, 15:12

14

Попробуй так:

C++
1
2
3
4
void __fastcall TForm1::Edit1KeyPress(TObject *Sender, char &Key)
{
if(Key<'0' || Key>'9')Abort();
}

Или так:

C++
1
2
if ((Key >='0') && (Key <= '9')) {}
else Key = 0;

Ну, или ещё так

C++
1
2
3
4
5
6
7
8
9
void __fastcall TForm1::Edit1KeyPress(TObject *Sender, char &Key)
{
            Set <Char,'0','9'> digit;
            digit<<'0'<<'1'<<'2'<<'3'<<'4'<<'5'<<'6'<<'7'<<'8'<<'9';
            if (! digit.Contains(Key) && Key!=8) {
            Key=0;
            }
 
}



0



0 / 0 / 0

Регистрация: 03.07.2009

Сообщений: 5

04.07.2009, 23:09

15

Стасёнок, все хорошо, только это, так понимаю для С++ билдера… Не плохо было бы посмотреть как оно выглядит для вижл С++



0



Стасёнок

274 / 200 / 33

Регистрация: 18.04.2009

Сообщений: 177

05.07.2009, 11:35

16

В событии KeyPress попробуй так:

C++
1
if (Key'0' || Key;'9') Key = 0;



0



Эксперт JavaЭксперт С++

8384 / 3616 / 419

Регистрация: 03.07.2009

Сообщений: 10,708

06.07.2009, 14:29

17



0



0 / 0 / 1

Регистрация: 29.01.2010

Сообщений: 68

01.02.2010, 20:35

18

Добрый вечер.Помогите пожалуйста. Если число,введенное в textbox1 равно 2,то в textbox2 вывести 5,а если число введенное в textbox1 равно 3,то в textbox2 вывести 6. Как это реализовать??



0



Konctantin

969 / 772 / 171

Регистрация: 12.04.2009

Сообщений: 1,700

01.02.2010, 20:45

19

Запихнуть в событие TextChenged

C#
1
textbox2.Text = (int.Parse(textbox1.Text) * 2).ToString();



0



0 / 0 / 1

Регистрация: 29.01.2010

Сообщений: 68

01.02.2010, 20:47

20

Спасибо!



0



  • Ввод ключа продукта для windows 10 при установке
  • Ввод в домен windows server 2019
  • Весь трафик через прокси windows 10
  • Ветка реестра автозагрузка windows 10
  • Ввод windows server 2016 в домен