ckay
ckay

Reputation: 66

Validate integer column

I use row validating for a telerik radgridview and use something like this for string values:

if (string.IsNullOrEmpty((string)row.Cells[3].Value)){
   e.Cancel = true;
   row.ErrorText = "Errortext";
   MessageBox.Show(row.ErrorText);
} else {
  row.ErrorText = string.Empty;
}

How do I validate an integer value? Integer has no IsNullOrEmpty and a value of 0 should be valid.

Upvotes: 0

Views: 123

Answers (2)

chambo
chambo

Reputation: 491

TryParse is your best bet for ensuring a string is an integer.

https://msdn.microsoft.com/en-us/library/system.int32.tryparse(v=vs.110).aspx

int someValue = -1;
if (Int32.TryParse(row.Cells[3].Value.ToString(), someValue))
{
    // Definitely an integer

    // Perform additional validation... someValue >= 0, etc.
}
else
{
    // Not an integer
}

Upvotes: 1

Bruno Ferreira
Bruno Ferreira

Reputation: 484

You could check the type before try to validade the value like this:

        var x = 1;
        var type = row.Cells[3].Value.GetType();
        switch (Type.GetTypeCode(type))
        {
            case TypeCode.Int32:
                // It's an int
                if(row.Cells[3].Value == null || row.Cells[3].Value < 0){
                   e.Cancel = true;
                   row.ErrorText = "Positive number is required";
                   MessageBox.Show(row.ErrorText);
                }
                break;

            case TypeCode.String:
                // It's a string
                if (string.IsNullOrEmpty((string)row.Cells[3].Value)){
                   e.Cancel = true;
                   row.ErrorText = "Errortext";
                   MessageBox.Show(row.ErrorText);
                }
                break;
        }

Upvotes: 0

Related Questions