Click here to Skip to main content
15,314,714 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am write the code for Listbox for calculating the sum of Total Numeric Values in present in ListBox.
i geting error like this-Cannot implicitly convert type 'int' to 'string'
Error shows here this line- TotalFees.Text = Total;
My ListBox values are this type

help me anyone

What I have tried:

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
       int Total;
       foreach (string Str in ListBox1.Items)
           Total = (Total + int.Parse(Str));

       TotalFees.Text = Total;
Updated 25-Mar-19 5:49am

TotalFees.Text = Total.ToString();
Member 14083059 25-Mar-19 11:29am
now i am getting error this line Total = (Total + int.Parse(Str));
Error comment is - Use of unassigned local variable 'Total'
Gerry Schmitz 25-Mar-19 11:35am
What "error"? It's not the same thing as before.
Member 14083059 25-Mar-19 11:37am
Use of unassigned local variable 'Total'
Chris A Clarke 25-Mar-19 14:10pm
Try initializing Total.

int Total = 0;

Then for fun try

var Total = ListBox1.Items.Cast<int>().Sum(); /// Textbox.Text = Total.ToString() or remove Total all together go to the TextBox.Text
Richard Deeming 26-Mar-19 16:00pm
Cast<int> won't work if the items are strings, which the foreach loop suggests is the case. :)
int Total = ListBox1.Items.Cast<string>().Select(int.Parse).Sum();
It is quite easy to solve this:
TotalFees.Text = Total.ToString();
int Total = 0; // set Total to zero to start
foreach (string Str in ListBox1.Items)
    Total = (Total + int.Parse(Str));

You need to initialise Total before using it the first time. Just modify the code as above.
Member 14083059 25-Mar-19 12:02pm
i used as above suggested code but still getting new error-"Unable to cast object of type 'System.Web.UI.WebControls.ListItem' to type 'System.String'."
This line- foreach (string str in ListBox1.Items)
Richard MacCutchan 25-Mar-19 14:17pm
ListBox items are not strings, please make use of the documentation: ListBox.Items Property (System.Windows.Forms) | Microsoft Docs[^]
Chris A Clarke 25-Mar-19 14:17pm
Ah ... WebControl ListItems have Text and Value string properties...

Using the foreach(ListItem str in ListBox1.Items)
Total += int.Parse(str.Value);


Total = ListBox1.Items.Sum( c => Int.Parse(c.Value));

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900