Help, how to Make textbox accept numbers only windows form c++

Hesham AbdMalek Ramadan 1 Reputation point
2021-12-20T19:42:57.787+00:00

how to Make textbox accept numbers only windows form c++

Developer technologies C++
{count} votes

3 answers

Sort by: Most helpful
  1. Castorix31 90,521 Reputation points
    2021-12-20T19:56:03.983+00:00

    There are several methods (KeyPress handling, SHLimitInput, ...), but you should use a NumericUpDown

    1 person found this answer helpful.

  2. Minxin Yu 13,501 Reputation points Microsoft External Staff
    2021-12-22T01:39:31.027+00:00

    Hi, @Hesham AbdMalek Ramadan
    Try to use "[^0-9.]" // added one point

    if (System::Text::RegularExpressions::Regex::IsMatch(textBox1->Text, "[^0-9.]"))
    {
    MessageBox::Show("Please enter only numbers.");
    textBox1->Clear();
    }

    159483-gif1.gif

    Best regards,

    Minxin Yu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

  3. Minxin Yu 13,501 Reputation points Microsoft External Staff
    2021-12-21T05:35:13.1+00:00

    Hi, @Hesham AbdMalek Ramadan

    You could try to use the snippet below in textbox keypress event. It can only accept the input of numbers 0-9, backspace and decimal point.

    8 stands for backspace,
    48 stands for number 0,
    57 stands for number 9,
    46 stands for decimal point.

    private: System::Void textBox1_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e)  
    {  
    	if (!(e->KeyChar == 8 || (e->KeyChar >= 48 && e->KeyChar <= 57) || e->KeyChar == 46))  
    	{  
    		e->Handled = true;  
    	}  
    }  
    

    Best regards,

    Minxin Yu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.