验证整数列

时间:2017-01-06 15:02:10

标签: c# winforms validation

我对telerik radgridview使用行验证,并使用类似这样的字符串值:

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

如何验证整数值? Integer没有IsNullOrEmpty,值0应该有效。

2 个答案:

答案 0 :(得分:0)

您可以在尝试验证值之前检查类型:

        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;
        }

答案 1 :(得分:0)

TryParse是确保字符串为整数的最佳选择。

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
}