c# - 在标签上加载总和

标签 c# mysql asp.net

我正在尝试在 lblPriceToBe 上加载 txtQuantity.Text 和 lblPice.Text 的总和。我正在使用此代码加载我的 lblprice。

private void GetData()
{
    SqlConnection connection = new SqlConnection("Data Source = localhost\\SQLEXPRESS;Initial Catalog = MejOnlineManagementDB00;Integrated Security=True;");
    connection.Open();
    SqlCommand sqlCmd = new SqlCommand(@"SELECT price,productType
                                        FROM Products3
                                        WHERE productName='" + DropDownList1.SelectedItem.Value.ToString() + "'", connection);
    SqlDataReader rdr = sqlCmd.ExecuteReader();
    if (rdr.HasRows)
    {
        while (rdr.Read())
        {
            lblPrice.Text = rdr.GetValue(0).ToString(); //  if price is  string use GetString(0))
            lblProdType.Text = rdr.GetValue(1).ToString();
        }
    }
    connection.Close();
    //DropDownList End of Area
}

在我得到 mysql 数据库的价格后,我将它乘以 txtQuantity

protected void btnCalculate_Click(object sender, EventArgs e)
{
    double Quantity = Convert.ToDouble(txtQuantity.Text);
    double Price = Convert.ToDouble(lblPrice.Text);
    double sum;
    sum = Quantity * Price;
    //Output
    sum = Convert.ToDouble(lblPriceToBe.Text);
}

然后我得到这个错误

An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code

附加信息:输入字符串的格式不正确。

这段代码的重点:

sum = Convert.ToDouble(lblPriceToBe.Text);

最佳答案

这意味着 lblPriceToBe.Text 中的值不可转换为 double。它可能为空或任何其他我们无法转换为 double 的值。在这种特殊情况下 double.TryParse将帮助您确定输入是否可转换,如果转换成功,它还会为您提供转换结果(否则将为 0.0);所以你想要做的是:

protected void btnCalculate_Click(object sender, EventArgs e)
{
    double Quantity,Price,sum;
    bool canProcess=true;
    if(!double.TryParse(txtQuantity.Text,out Quantity)
    {
      // conversion failed
      lblPriceToBe.Text="Invalid quantity"
      canProcess=false;
    }
    if(!double.TryParse(lblPriceToBe.Text,out Price)
    {
      // conversion failed
      lblPriceToBe.Text="Invalid Price"
      canProcess=false;
    }
    if(canProcess)
    {
    sum = Quantity * Price;
    //Output
    lblPriceToBe.Text=sum.ToString();
    }

}

关于c# - 在标签上加载总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36992318/

相关文章:

c# - 每个线程的处理时间?

c# - 有理数的最短十进制表示

c#程序sql语法错误

c# - 有没有办法将 aspx 文件放入 Visual Studio 2008 .NET 3.5 的类库中?

javascript - 如何从分配的隐藏字段值中获取文本框值

c# - MDI 应用程序中的 "Partially modal"表单

c# - 如何通过 Windows Mobile 6 使用存储管理器 API 格式化 SD 卡

php - 从 MySQL 中的多个表中排序产品价格

mysql - Oracle SQL 查询帮助查找一列具有两个可能值的条目

c# - 从网格中获取文本