我正在尝试在 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/