My `TextChangedEvent` fires on `FormLoad` event and gives an error. Input string not in correct format

41 views Asked by At

Here is my TextChanged event.

private void Price_Discount_MarginBox_TextChanged(object sender, EventArgs e)
{
    if (Convert.ToDecimal(profit_MarginTextBox.Text) > 0)
    {
        Company_List_PriceTextBox.Text = ((Convert.ToDecimal(list_PriceTextBox.Text) - (Convert.ToDecimal(list_PriceTextBox.Text) * (Convert.ToDecimal(discountTextBox.Text) / 100))) / Convert.ToDecimal(profit_MarginTextBox.Text)).ToString();
    }
    else
        Company_List_PriceTextBox.Text = list_PriceTextBox.Text;
}

The various text boxes are set with a string value of 0.00 unless populated with the data from the bound Data Table. The textChanged event is on three different textbox.

1

There are 1 answers

2
Anik Islam Abhi On BEST ANSWER

All you have to do is add check a data is valid string or not . if text is null it won't consider null = 0 .

Try this

decimal demo;
if(decimal.TryParse(profit_MarginTextBox.Text,out demo)){
if (Convert.ToDecimal(profit_MarginTextBox.Text) > 0)
    {
        Company_List_PriceTextBox.Text = ((Convert.ToDecimal(list_PriceTextBox.Text) - (Convert.ToDecimal(list_PriceTextBox.Text) * (Convert.ToDecimal(discountTextBox.Text) / 100))) / Convert.ToDecimal(profit_MarginTextBox.Text)).ToString();
    }
    else
        Company_List_PriceTextBox.Text = list_PriceTextBox.Text;
}

From your request

Would you be able to tell me how to put Line 5 on multiple lines for easier reading?

Try this

decimal margin = Convert.ToDecimal(profit_MarginTextBox.Text);
decimal price = Convert.ToDecimal(list_PriceTextBox.Text);
decimal discount = Convert.ToDecimal(discountTextBox.Text);
decimal total = 0;
if (margin > 0)
   total = (price - (price*(discount/100)))/margin;
else
   total = price;
Company_List_PriceTextBox.Text = total.ToString();