'C# system.FormatException: 'Input string was not in a correct format.' [duplicate]
I am getting the above error for the below block of coding. I have tried several articles in this page for similar error. Still could not find a solution. Please help.
private void txtDiscount_TextChanged(object sender, EventArgs e)
{
// Calculate Discount and Final Fee
double FinalFee;
double CourseFee1;
double Disc;
CourseFee1 = Convert.ToDouble(lblCourseFee.Text);
Disc = Convert.ToDouble(txtDiscount.Text);
FinalFee = CourseFee1 - (CourseFee1 * (Disc / 100));
//MessageBox.Show(CourseFee1 + " " + Disc + " " + FinalFee.ToString("N2"));
if (Disc > 40)
{
string message = "Maximum Discount is 40% ";
string title = "Discount Maximum Limit Exceeded";
MessageBoxButtons buttons = MessageBoxButtons.OK;
DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Warning);
}
else
{
lblFinalFee.Text = FinalFee.ToString("N2");
}
}
Solution 1:[1]
The error message is plain english, your debugger will point you to the exact line it occurs. We cannot change what the user types into your text fields. If it is not a double, it cannot be converted.
You can either catch that exception, or use Double.TryParse if you want to handle it with an if instead of an exception block. But you have to handle it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nvoigt |
