C# - How To Get The Average Value From DataGridView Column In C#

datagridview column average value

C# - How To Get The Average Value In DataGridView Column Using C#

                                                                                                                         

In This C# Tutorial  We Will See How To Get The Average Value From DataGridView  Column And Display It In TextBox Using CSharp Programming Language.


Project Source Code:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Csharp_Datagridview_Column_Cells_Average : Form
    {
        public Csharp_Datagridview_Column_Cells_Average()
        {
            InitializeComponent();
        }

  private void Csharp_Datagridview_Column_Cells_Average_Load(object sender, EventArgs e)
        {
            // populate datagridview with some data
            Random r = new Random();
            for (int i = 0; i <= 10; i++)
            {
                dataGridView1.Rows.Add("First Name" + i.ToString(), "Last Name" + i.ToString(), r.Next(20, 65).ToString());
            }

            dataGridView1.AllowUserToAddRows = false;

            // method 1
           textBoxAvg.Text = (from DataGridViewRow row in dataGridView1.Rows
                          where row.Cells[2].FormattedValue.ToString() != string.Empty
                           select Convert.ToInt32(row.Cells[2].FormattedValue)).Average().ToString("00.000");*/

            // method 2
            int sum = 0;
            double avg = 0;
            int dataCount = dataGridView1.Rows.Count;
            for(int i = 0; i <= dataGridView1.Rows.Count-1; i++)
            {
                sum = sum + int.Parse(dataGridView1.Rows[i].Cells[2].Value.ToString());
            }
            avg = (double)sum/dataCount;
            textBoxAvg.Text = avg.ToString("00.000");

            // method 3
            int[] columnData = (from DataGridViewRow row in dataGridView1.Rows
                                where row.Cells[2].FormattedValue.ToString() != string.Empty
                                select Convert.ToInt32(row.Cells[2].FormattedValue)).ToArray();

            textBoxAvg.Text = columnData.Average().ToString("00.000");
        }
    }
}


      
///////////////OUTPUT:





c# datagridview average column value
c# datagridview average column value

Share this

Related Posts

Previous
Next Post »