@NotPoliticallyCorrect has pointed you in the right direction - the content of one of the textboxes is not an integer.
The problem with using
Convert.ToInt32
is that it will, as you have discovered, throw an exception if the string is not an integer. For example "1" will be ok, "12345" will be ok but both "$35" and "14.6" will cause the failure you have observed.
A better solution is to use one of the integer
parsing methods - see
How to: Convert a String to a Number (C# Programming Guide)[
^]
There are other issues with your code ...
string total = (BillingGridView.Rows[i].Cells[7].Text);
is throwing a compile error for me, it should probably be
String total = (BillingGridView.Rows[i].Cells[7].Value.ToString());
The line
int vat = Convert.ToInt32(VATPerLabel.Text.ToString());
has an unnecessary
.ToString()
call in it ...
VATPerLabel.Text
is already a string! Similarly
GTotal += Convert.ToInt32(total.ToString());
doesn't need the
.ToString()
as you have already declared
total
as a
String
.
The line
int billtotal = Convert.ToInt32(BillTotalLabel.Text);
has an unnecessary conversion in it ... you have just set the BillTotalLabel.Text to be
GTotal.ToString();
so that line should be
int billtotal = GTotal;
So you should have something like this (note I have not tested this)
private void GrandTotal()
{
int GTotal = 0;
int res;
for (int i = 0; i < BillingGridView.Rows.Count; i++)
{
String total = (BillingGridView.Rows[i].Cells[7].Value.ToString());
if(int.TryParse(total, out res))
GTotal += Convert.ToInt32(total);
}
BillTotalLabel.Text = GTotal.ToString();
VATValueLabel.Text = "";
if (String.IsNullOrWhiteSpace(BillTotalLabel.Text))
return;
int billtotal = GTotal;
int vat;
if (int.TryParse(VATPerLabel.Text, out vat))
{
int totalaftervat = billtotal*vat/100;
VATValueLabel.Text = totalaftervat.ToString();
}
}
I will leave you with one final comment - I don't think you want to be using
int
for some of these variables - decimal or double might be more appropriate