2012-12-05 87 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"); 
     } 
    } 

}