Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating whether a textbox contains only numbers

So I have an idea, because i find it hard to make a code for txtbox that will only allow integer and not a letters in mysql using c#. My Plan is why not set the database column into integer instead of typical varchar and if ever you put a letter of course it will turn and exception so in that case I want to catch the exception and prompt a messagebox saying "Please enter only integer". What do you think?

like image 399
Jayseer Avatar asked Mar 14 '13 00:03

Jayseer


2 Answers

Visual studio has built in support for this (and you may also achieve it via coding). Here's what you need to do:

  • Switch to design view from markup view.
  • Now click on design view and press Ctrl+Alt+X.
  • From the toolbox that opens click on Validation and drag a compare validator near your TextBox.
  • Right click on the compare validator and choose properties, now locate ErrorMessage and write "Alert: Type only Number".
  • In Control to Validate choose your control.
  • In the Operator choose DataTypeCheck and in the Type choose Integer.

Also via coding you can get it as:

protected void Button1_Click(object sender, EventArgs e)
{
    int i;
    if (!int.TryParse(textBox.Text, out i))
    {
        Label.Text = "This is a number only field";
        return;
    }
}
like image 26
Prince Sharma Avatar answered Nov 13 '22 05:11

Prince Sharma


It's a good idea to use the correct column datatype for what you plan to store in it, but it's very easy to check whether a string contains only numbers - just parse and see if an error is returned:

int parsedValue;
if (!int.TryParse(textBox.Text, out parsedValue))
{
    MessageBox.Show("This is a number only field");
    return;
}

// Save parsedValue into the database
like image 66
Simon MᶜKenzie Avatar answered Nov 13 '22 06:11

Simon MᶜKenzie