rai nalasa rai nalasa - 7 months ago 20
SQL Question

Loading Sum on label

I am trying to load the sum of txtQuantity.Text and lblPice.Text on lblPriceToBe..I'm loading my lblprice with this code.

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
}


After I got the price on mysql database I multiply it with 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);
}


and then I get this error


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


Additional information: Input string was not in a correct format.

that point on this code:

sum = Convert.ToDouble(lblPriceToBe.Text);

Answer

That means the value in the lblPriceToBe.Text is not convertible to double. it may be empty or any other values which we cannot convert to double. In such particular scenarios double.TryParse will help you to determine whether the input is convertible or not, it will also give you the converted result if the conversion is successful( else it will be 0.0); SO what you want to do is:

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

}