0

我正在尝试LinqToSql在 Visual Studio 2010(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");
        }
    }

}

我不知道我错过了什么。

4

2 回答 2

1

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

int number;
bool IsNumber = int.TryParse("someString", out number); 
于 2012-12-05T13:48:36.357 回答
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");
        }
    }

}
于 2012-12-05T13:55:45.643 回答