使用LinqToSql验证错误(Visual Studio 2010)

时间:2012-12-05 13:44:30

标签: asp.net linq-to-sql

我正在尝试在Visual Studio 2010中使用LinqToSql(Asp.net,C#)。 插入/删除/更新记录工作正常,但如果我在int字段中写字母,程序会以非常漂亮的方式中断。

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

}

我不知道我错过了什么。

2 个答案:

答案 0 :(得分:1)

使用int.TryParse,如果字符串无法转换为int,则返回0。

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

答案 1 :(得分: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");
        }
    }

}