0

I using this code for validation integer input on datagridview.

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if (string.IsNullOrEmpty(e.FormattedValue.ToString()))
    {
        MessageBox.Show("Cannot Empty!");
        e.Cancel = true;
    }
    else if (...)
    {
        MessageBox.Show("Only can input number!");
        e.Cancel = true;
    }
}

and now I have trouble on the code that I put a dots. is there any that can give you an idea ? whether the use regex can be used in these conditions ?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Underdog
  • 129
  • 13
  • [check if the string is numeric](http://stackoverflow.com/questions/894263/how-do-i-identify-if-a-string-is-a-number) – nlloyd Jul 01 '16 at 17:26

2 Answers2

1

Just use int.Tryparse and call a method to it, something like this, but I haven't checked this code, just a quick example.

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        if (string.IsNullOrEmpty(e.FormattedValue.ToString()))
        {
            MessageBox.Show("Cannot Empty!");
            e.Cancel = true;
        }
        else if (!isNumeric(e.FormattedValue.ToString())
        {
            MessageBox.Show("Only can input number!");
            e.Cancel = true;
        }

    }

Put a method somewhere like this

    public static bool IsNumeric(string theNumber)
    {
        if (theNumber == null) throw new ArgumentNullException("theNumber");

        int n;
        bool isNumeric = int.TryParse(theNumber, out n);
        return isNumeric;
    }
prospector
  • 3,389
  • 1
  • 23
  • 40
1
int n;
bool isNumeric = int.TryParse(e.FormattedValue.ToString(), out n);

put this code before your "if" and then check isNumeric in else if block

Siavash Rostami
  • 1,883
  • 4
  • 17
  • 31