如何在c#中验证价格范围值

时间:2015-07-09 11:14:55

标签: c# asp.net

我正在为我的销售和库存添加材料。到目前为止,我需要进行验证,在添加材料时,销售价格必须大于购买价格。

这是我的代码,我在if / else语句中遇到错误,其中我的txtPurchasePrice和txtSellingPrice的值是十进制的(18,2)。

protected void btnAdd_Click(object sender, EventArgs e)
{
    if (txtSellingPrice.Text >= txtPurchasePrice.Text)
    {
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "INSERT INTO Materials VALUES (@UnitID, @Name, @SellingPrice, @PurchasePrice, " +
            "@Description, @Available, @CriticalLevel, @Maximum, @Status, @DateAdded, @DateModified)";                
        cmd.Parameters.AddWithValue("@UnitID", txtUnitID.Text);
        cmd.Parameters.AddWithValue("@Name", txtName.Text);
        cmd.Parameters.AddWithValue("@SellingPrice", txtSellingPrice.Text);
        cmd.Parameters.AddWithValue("@PurchasePrice", txtPurchasePrice.Text);
        cmd.Parameters.AddWithValue("@Description", txtDesc.Text);
        cmd.Parameters.AddWithValue("@Available", "0");
        cmd.Parameters.AddWithValue("@CriticalLevel", txtCritical.Text);
        cmd.Parameters.AddWithValue("@Maximum", txtMax.Text);
        cmd.Parameters.AddWithValue("@Status", "Available");
        cmd.Parameters.AddWithValue("@DateAdded", DateTime.Now);
        cmd.Parameters.AddWithValue("@DateModified", DBNull.Value);
        cmd.ExecuteNonQuery();
        con.Close();
        Helper.AddLog("1", "Add", "Added a new Material");
        Response.Redirect("~/Materials/Default.aspx");
    }
    else
    {
        error.Visible = true;
    }
}

我的错误

  

CS0019:运算符'> ='无法应用于'string'类型的操作数   和'字符串'

为什么不能使用>=<=||<>?在这种情况下?

4 个答案:

答案 0 :(得分:4)

我假设txtSellingPricetxtPurchasePriceTextBox控件,因此他们的Text属性属于string类型。您不能使用>=,因为它没有语义含义。您需要先将文本解析为decimal

var sellingPrice = decimal.Parse(txtSellingPrice.Text);
var purchasePrice = decimal.Parse(txtPurchasePrice.Text);

if (sellingPrice >= purchasePrice)
{
   // stuff
}

如果您不确定该文字是有效的decimal值,请使用decimal.TryParse

decimal sellingPrice;
if (!decimal.TryParse(txtSellingPrice.Text, out sellingPrice))
{
   // Not a valid decimal, do something.
}

decimal purchasePrice;
if (!decimal.TryParse(txtPurchasePrice.Text, out purchasePrice))
{
   // Not a valid decimal, do something.
}

if (sellingPrice >= purchasePrice)
{
   // stuff
}

答案 1 :(得分:2)

Hwo的字符串是否大于另一个字符串?

在进行比较之前,您需要将字符串转换为数值。

由于您要处理资金,您应该使用Decimal

if (Decimal.Parse(txtSellingPrice.Text) >= Decimal.Parse(txtPurchasePrice.Text))

答案 2 :(得分:1)

要比较两个字符串的数值,您必须将它们解析为数字类型,例如加倍!

答案 3 :(得分:0)

使用Convert.ToDecimal(txtSellingPrice.Text)&gt; = Convert.ToDecimal(txtPurchasePrice.Text)

无法像那样比较字符串值

相关问题