Verifying Input RRS feed

  • Question

  • How in C# can I verify that the input into a text box is all numeric and equal to 10?
    Sunday, November 25, 2018 3:12 AM

All replies

  • https://www.oreilly.com/library/view/c-cookbook/0596003390/ch01s08.html

    if (!isNumeric(textbox1.text)) { e.cancel = true; //cannot leave if not numeric //put out messagebox. } else { //is numeric int check = int.parse(textbox.text); if (check != 10) { e.cancel; //cannot leave if not = 10 // put out messagebox } } https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.leave?view=netframework-4.7.2 https://stackoverflow.com/questions/1135299/microsoft-visual-studio-and-c-how-to-visually-add-events-to-controls Make the IsNumeric() function

    do the check inside the Leave() event with the above code. You do an e.Cancel = true, then user can't leave the textbox.

    Sunday, November 25, 2018 5:01 AM
  • You can use Linq for that :

    if(txtBox1.Text.All(x=> Char.IsNumeric(x)))
       if(Convert.ToInt32(txtBox1.Text) == 10)
          Console.WriteLine("The text is number and 10");

    You will need to add using statement for System.Linq like:

    using System.Linq;

    You can create a common method using the above code and use it.

    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered"Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]

    Blog | LinkedIn | Stack Overflow | Facebook
    profile for Ehsan Sajjad on Stack Exchange, a network of free, community-driven Q&A sites

    Sunday, November 25, 2018 5:08 AM

  •    How in C# can I verify that the input into a text box is all numeric and equal to 10?

    Check if this works too:

       if( textBox1.Text.Trim( ) == "10") . . .


    Or maybe you mean that the length is equal to 10?

    • Edited by Viorel_MVP Sunday, November 25, 2018 7:45 AM
    Sunday, November 25, 2018 7:33 AM

    A more Crashsafe way, using a try:

    bool isThisAnInt = false;
     bool success = false;

                isThisAnInt = int.TryParse(textbox1.txt, out int theInt);
                if ((textbox1.Length()<=100) && (isThisAnInt) && (theInt == 10)) )

                    success = true;

    This will first verify the length of the input to stop a potensial attacker to crash your system by typing in a huge number,

    • Edited by ThisNewbie Sunday, November 25, 2018 10:13 AM
    Sunday, November 25, 2018 10:09 AM