-1

I'm really having a hard time with this. This code is suppose to be solving a total payment and put it into the sub total TextBox, but when i try to convert it to double (because the prices have decimals), this is what it came up with. I've tried int and it didnt have any problems.

Any solutions for this?

double i = 0;
double j = 0;
double k = 0;
i = 0;
j = 0;
k = 0;

try
{
    j = lstvProds.Items.Count;
    for (i = 0; i <= j - 1; i++)
    {
        k = k + Convert.ToDouble(lstvProds.Items[i].SubItems[4].Text);
    }

    //double l = Convert.ToDouble(k);

}

catch (Exception ex)
{
    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return k;
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Sam
  • 19
  • 6
  • oops sorry! it's there now – Sam Oct 13 '16 at 13:25
  • 1
    why is i declared as double? try using int as type for i... – Philip W Oct 13 '16 at 13:27
  • will try! @Philip – Sam Oct 13 '16 at 13:28
  • This question is not unique. Please read [ask] and share your research. It just means that for some value of `i`, `lstvProds.Items[i].SubItems[4].Text` will return a value that cannot be parsed as double. See for example the [duplicate](http://stackoverflow.com/questions/11399439/converting-string-to-double-in-c-sharp). If that doesn't answer your question, then [edit] your question to include a [mcve] including the input for which this code fails. Edit: alright, reopened, the problem was the `ListView.Items.Item[string]` indexer being resolved for a call with a `double`... – CodeCaster Oct 13 '16 at 13:28
  • @PhilipW has a good point, but that's not what is wrong here. Try stepping through each iteration of the for loop. What is the last value you see for lstvProds.Items[i].SubItems[4].Text before the exception is thrown? – Tim Copenhaver Oct 13 '16 at 13:29
  • @philipw, that worked like a charm XD i just realized it now! THANK YOU SO MUCH ^w^ – Sam Oct 13 '16 at 13:30
  • 1
    Thats the problem with the ListView: everything is string and you need code to convert it back (and populate each cell). Use a DataGridView and you can retain the datatype – Ňɏssa Pøngjǣrdenlarp Oct 13 '16 at 13:30
  • Thank you guys for your time and help! ^w^ Appreciated!~ – Sam Oct 13 '16 at 13:31

1 Answers1

0

Just to make it clear, I convert my comment to an answer and elaborate the underlying problem:

To be clear: The problem was a compile error, not an exception during runtime.

The reason for it was the following part:

lstvProds.Items[i]

The Items[] operator is overloaded with a string and an integer parameter. The integer version returns the ith element, the string version looks for a matching item in the list with the same name.

That's the reason for the Error: 'i' is a double. Used with an integer, everything is fine...

PS: parsing the double to a string could lead to a completly different functionality...

Philip W
  • 781
  • 3
  • 7