Search code examples
c#listboxlistboxitem

C# Unable to cast object of type 'TCSCapstone.frmInventory' to type 'System.IConvertible'


I'm trying to add up all the values in a Listbox which the Listbox is populated by the value of two other list boxes multiplied together. It's essentially a sum of a Listbox.

I keep getting an error and I looked it up and everyone else has similar issues with similar problems. It has something to do with the ToInt32 or the ToString, I just cannot fix it. Whenever I click my button to load the Listbox which executes that loop, it gives me the error.

Please help, this is all I need left.

         int i = 0, result = 0;
         while (i < lstTotalPrices.Items.Count)
         {
             result += Convert.ToInt32(lstTotalPrices.Items[i++]);
         }

         txtTotal.Text = Convert.ToString(result);

Solution

  • Based on comments and chat this should work:

    int i = 0; 
    decimal result = 0; 
    while (i < lstTotalPrices.Items.Count) 
    { 
        result += ((frmInventory)lstTotalPrices.Items[i++]).TotalPrice; 
    }
    

    Although a tidier solution would be

    int i = 0;
    decimal result = 0;
    
    foreach (var item in lstTotalPrices.Items)
    {
        result += item.TotalPrice;
    }