Question how to find sum of column in listview?

Joined
Dec 16, 2020
Messages
8
Programming Experience
Beginner
C#:
String[] arr = new String[4];
arr[0] = pname.Text;
arr[2] = qtytextBox.Text;
arr[1] = pricy.Text;
double f1, g1, j;

double.TryParse(qtytextBox.Text, out f1);
double.TryParse(pricy.Text, out g1);

j = f1 * g1;

if (j > 0)
    arr[3] = j.ToString();

ListViewItem listy = new ListViewItem(arr);
listView1.Items.Add(listy);
 
Last edited by a moderator:
Welcome to the forums.

In the future please don't just dump code and expect us to figure out what you are trying to do. Please explain in detail what you are trying to do and what problem you are running into. A one line subject line for the topic doesn't cut it.

Also, when posting code, please put it in code tags. This helps preserve the formatting and makes it easier to read the code.
 
In your example @Kakashi Moshimo it will always be four. Below is a dynamic example.
How to count columns in a ListView:
        private void NumberOfColumnsInAListViewExample()
        {
            var alistView = new ListView();
            var name = "Name";
            var price = "200";
            var qty = "10";
            List<string> lst = new List<string>(4)
            {
                name,
                price,
                qty
            };
            double j;
            double.TryParse(qty, out double f1); double.TryParse(price, out double g1);
            j = f1* g1;
            if (j > 0)
            {
                lst.Add(j.ToString());
            }
            alistView.Items.Add(new ListViewItem(lst.ToArray()));
            MessageBox.Show($"Number of columns={alistView.Items[alistView.Items.Count - 1].SubItems.Count}");
        }
 
In your example @Kakashi Moshimo it will always be four. Below is a dynamic example.
How to count columns in a ListView:
        private void NumberOfColumnsInAListViewExample()
        {
            var alistView = new ListView();
            var name = "Name";
            var price = "200";
            var qty = "10";
            List<string> lst = new List<string>(4)
            {
                name,
                price,
                qty
            };
            double j;
            double.TryParse(qty, out double f1); double.TryParse(price, out double g1);
            j = f1* g1;
            if (j > 0)
            {
                lst.Add(j.ToString());
            }
            alistView.Items.Add(new ListViewItem(lst.ToArray()));
            MessageBox.Show($"Number of columns={alistView.Items[alistView.Items.Count - 1].SubItems.Count}");
        }
The OP is asking how to sum the values in a column, not count the columns.
C#:
var sum = myListView.Items
                    .Cast<ListViewItem>()
                    .Sum(lvi =>
                         {
                             double.TryParse(lvi.SubItems[columnIndex].Text, out var number);

                             return number;
                         });
If you know the values will be valid, that simplifies a bit:
C#:
var sum = myListView.Items
                    .Cast<ListViewItem>()
                    .Sum(lvi => double.Parse(lvi.SubItems[columnIndex].Text));
 
If you want to sum multiple columns:
C#:
var column1Sum = 0.0;
var column2Sum = 0.0;

foreach (ListViewItem item in myListView.Items)
{
    double.TryParse(item.SubItems[columnIndex1].Text, out var number1);
    double.TryParse(item.SubItems[columnIndex2].Text, out var number2);

    column1Sum += number1;
    column2Sum += number2;
}
 
C#:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace StockPOS
{
    public partial class Cashys : Form
    {
        SqlDataAdapter adapter;
        DataTable table;
        SqlCommand cmd;

        public Cashys()
        {
            InitializeComponent();
        }

        private void TextBox10_TextChanged(object sender, EventArgs e)
        {

        }

        private void Button1_Click(object sender, EventArgs e)
        {
            this.Hide();
            Form1 dish = new Form1();
            dish.Show();
        }

        private void Productsbutton_Click(object sender, EventArgs e)
        {
            this.Hide();
            Products dish = new Products();
            dish.Show();
        }

        private void Depositsbutton_Click(object sender, EventArgs e)
        {
            this.Hide();
            Deposits dish = new Deposits();
            dish.Show();
        }

        private void Button3_Click(object sender, EventArgs e)
        {
            this.Hide();
            Form1 dish = new Form1();
            dish.Show();
        }

        private void Panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void Cashys_Load(object sender, EventArgs e)
        {
            listView1.GridLines = true;
            listView1.View = View.Details;
            listView1.FullRowSelect = true;


            listView1.Columns.Add("Product Name", 150);
            listView1.Columns.Add("Price", 150);
            listView1.Columns.Add("Qty",150);
            listView1.Columns.Add("Total", 150);
          
        }
       
        public void SearchData(String ValueToSearch)
        {
          
            using (SqlConnection con = new SqlConnection(Properties.ApplicationSetting.ConnectionString()))
            {
              
                using (SqlCommand Query = new SqlCommand("usp_query", con))
                {
                    con.Open();
                    adapter = new SqlDataAdapter(cmd);
                    table = new DataTable();
                    adapter.Fill(table);
                    con.Close();

                }


            }
        }
     

        private void Search_Click(object sender, EventArgs e)
        {
            String Source = "Data Source=KAKASHI; Initial Catalog=SunvicDesigns; Trusted_Connection=Yes";
            SqlConnection con = new SqlConnection(Source);
            con.Open();
            MessageBox.Show("Connected to database");
            String SqlSelectQuery = "SELECT ProductName,ProductSize,ProductPrice FROM ProductDetails WHERE ProductID = " + int.Parse(ProductIDtxtBox3.Text);
            SqlCommand cmd = new SqlCommand(SqlSelectQuery, con);
            SqlDataReader dr = cmd.ExecuteReader();
          

            if (dr.Read())
            {
                pname.Text = (dr.GetValue(0).ToString());
                ProductsSizetextBox1.Text = (dr.GetValue(1).ToString());
                pricy.Text = (dr.GetValue(2).ToString());
               
            }
            con.Close();
        }

        private void Void_Click(object sender, EventArgs e)
        {
            String[] arr = new String[4];
            arr[0] = pname.Text ;
            arr[2] = qtytextBox.Text;
            arr[1] = pricy.Text ;
            ;
            double f1, g1, j;
            double.TryParse(qtytextBox.Text, out f1); double.TryParse(pricy.Text, out g1);
            j = f1 * g1;
            if (j > 0)

                arr[3] = j.ToString();


            ListViewItem listy = new ListViewItem(arr);
            listView1.Items.Add(listy);

          

        }

        private void ListView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void TottextBox_TextChanged(object sender, EventArgs e)
        {
          
        }
    }
}


I need to find sum of column 4
 
Last edited by a moderator:
I fixed the post like this:

insertcode.png
 
Sigh. That is a really bad practice to use your View as your Data Model. So you are querying for items with a particular ID and then putting values into textboxes. Then later you take the values from the textboxes and stick them into a listview, if a button is clicked. And now you want to sum up values from column 4 of the listview.

That is the old way of doing things back when PCs had limited RAM and CPU. The correct modern way to do things is to use your View to only reflect the values of your Data Model. Use the one of MVC, MVP, MVVM, etc. patterns. Pull your Data out of the database I and into a temporary object. When the button is clicked, add that temporary object into a list. Bond they listview to that list. To compute the sum of a column, iterate over the list items and compute the sum.
 
That's how you insert code when posting :) I fixed your post for you.
 
Are you saying that you can't see the screenshot in post 7 ?
 
What do you mean?
 
Back
Top Bottom