简体   繁体   中英

Validate user input C#

How can I check if the user has entered a number in a Text field? If they do enter data other than text I want an error message to display and loop back to take their input again.. Any help would be appreciated. Thanks.

Here's the code:

myCmd.CommandText = "INSERT INTO Guest(Guest_First_Name, Guest_Surname, Guest_Address, Guest_Postcode, Guest_Telephone, [Guest_E-mail])" + "VALUES(@Fname, @Sname, @Address, @Postcode, @Telephone, @Email)";

        myCmd.Parameters.Add("@Fname", OleDbType.Char).Value = firstName.Text;
        myCmd.Parameters.Add("@Sname", OleDbType.Char).Value = surname.Text;
        myCmd.Parameters.Add("@Address", OleDbType.Char).Value = address.Text;
        myCmd.Parameters.Add("@Postcode", OleDbType.Char).Value = postcode.Text;
        myCmd.Parameters.Add("@Telephone", OleDbType.Char).Value = telephone.Text;
        myCmd.Parameters.Add("@Email", OleDbType.Char).Value = email.Text;

        connect.Open();
        int rowsChanged = myCmd.ExecuteNonQuery();
        connect.Close();

        if (rowsChanged == 1)
        {
            MessageBox.Show("Record Inserted");
        }
        else
        {
            MessageBox.Show("Error: Record Not Inserted");
        }

Lets assume that textField is the name of field. Then you can do the following in C#:-

int num=0;
if(!(Int32.TryParse(textField,out num)))
{
Console.WriteLine("Error");
return;  // return an error at this point
}

You can also try the following (untested) :-

int num=0;
if(!(Int32.TryParse(textField,NumberStyles.None,CultureInfo.InvariantCulture,out num)))
{
Console.WriteLine("Error");
return;  // return an error at this point
}

In the first example, the NumberStyles defaults to Integer. Changing it to None might help.

Could use something like this:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    textBox1.Text = string.Concat(textBox1.Text.Where(char.IsLetter));
}

This wouldn't show any errors; anything other than letters would just be deleted.

int result;
if (int.TryParse(input.Text, out result))
{
    // it's a valid integer => you could use the result variable here
}

or if you want to validate in keypress,

private void txtbox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '')  
    {
        e.Handled = false; //Do not reject the input
    }
    else
    {
        e.Handled = true; //Reject the input
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM