2012-12-05 85 views
0

我试图在Visual Studio 2010(Asp.net,C#)中使用LinqToSql。 插入/删除/更新记录工作得很好,但如果我在int字段中写入字母,程序就会以非美丽的方式中断。使用LinqToSql验证错误(Visual Studio 2010)

在我DataClasses.Designer我:

partial void Insertproduct(product instance); 

,我添加其他类:

public partial class product 
{ 

    partial void OnPriceChanging(string value) 
    { 
     Regex Price = new Regex("^[A-Z0-9 a-z]*$"); 
     if (Precio.IsMatch(value) == false) 
     { 
      throw new Exception("Just numbers"); 
     } 
    } 

} 

我不知道我错过了什么。

回答

1

使用int.TryParse如果字符串不能转换为int,它将返回0。

int number; 
bool IsNumber = int.TryParse("someString", out number); 
1

您使用的正则表达式对验证“仅数字”是不正确的。使用这个:

public partial class Product 
{ 

    partial void OnPriceChanging(string value) 
    { 
     Regex price = new Regex("^[0-9]*$"); 
     if (!price.IsMatch(value)) 
     { 
      throw new Exception("Just numbers"); 
     } 
    } 

}