Reputation:
I want to sum the items in the list box by method, and I want to print the result on label1.
Code:
void sum()
{
...
}
int index = 0;
string[] numbers= new string[10];
private void button1_Click(object sender, EventArgs e) // Add Button
{
if (index < numbers.Length)
{
numbers[index] = textBox1.Text;
listBox1.Items.Add(numbers[index++]);
}
}
private void button2_Click(object sender, EventArgs e) // Sum calc button
{
...
}
Upvotes: 0
Views: 1245
Reputation: 37020
If you know that all the items in your ListBox
are numeric types, then you can just cast the collection to int
(or decimal
, etc.) and get the Sum
using System.Linq
. Note that this will throw an exception in the Cast()
method if the item in the list is not of the type we're trying to cast to:
// Add integers to listbox
listBox1.Items.AddRange(new object[] { 1, 2, 3, 4, 5 });
// Get the sum using Linq
int sum = listBox1.Items.Cast<int>().Sum();
If the list contains a mix of numeric types, but they can all be converted to the same type (like integers, doubles, and decimals) then we can convert them instead of cast:
// Initialize with an int, double, single, and decimal
listBox1.Items.AddRange(new object[] {1, 2.1, 3.2f, 4.3m});
// Use 'Convert' instead of 'Cast' (after casting to the base object type):
decimal sum = listBox1.Items.Cast<object>().Select(Convert.ToDecimal).Sum();
If any of the types are non-numeric, then you have to test to see if they can be converted before getting the sum. One way to do this is to use [numericType].TryParse
on the item.ToString()
value to do the conversion. This method is handy because it returns true
if the item can be converted, and sets the out
parameter to the converted value. If you want int
values only, use int.TryParse
. If you want more numeric types, try decimal.TryParse
:
// Initialize the array so it includes a non-numeric string type
listBox1.Items.AddRange(new object[] {"1", 2, 3.1, 4.2f, 5.6m});
decimal sum = 0;
foreach (var item in listBox1.Items)
{
decimal temp;
if (decimal.TryParse(item.ToString(), out temp))
{
sum += temp;
}
}
Upvotes: 2
Reputation: 96
You can use the UpdateLabel function to make the label value the sum.
private int Sum()
{
var sum = 0;
for(int i = 0; i < listBox1.Items.Count; i++)
{
if(int.TryParse(listBox1.Items[i].ToString(), out var n))
{
sum += n;
}
}
return sum;
}
private void UpdateLabel()
{
label1.text = Sum().ToString();
}
Upvotes: -1