Search code examples
c#databasedatagridviewoledb

How to count not-empty rows of each column in one datagridview and show numbers of rows in the second datagridview?


I have 2 datagridviews:

1 - Shows data from database.

2 - Has to show number of not-empty rows of each column in the first datagridview.

I tried this code, but it count every row:

     var count = dataGridView1.Rows.Cast<DataGridViewRow>().Where(row => !(row.Cells[0].Value == null || row.Cells[0].Value == DBNull.Value)).Count();

The second datagridview has to show distinct not-empty rows.

Please help to solve this problem.

Thank you for helping.


Solution

  • Try following :

                var count = Enumerable.Range(0, dataGridView1.Columns.Count) 
                    .Select(x => new { column = x, count = dataGridView1.Rows.Cast<DataGridViewRow>().Where(row => !(row.Cells[x].Value == null || row.Cells[x].Value == DBNull.Value)).Count() })
                    .ToList();
    

    Using a datatable

                var count1 = Enumerable.Range(0, dt.Columns.Count)
                    .Select(x => new { column = x, count = dt.AsEnumerable().Where(row => row[x] != DBNull.Value).Count() })
                    .ToList();
    

    Creating a datatable with results

                var count1 = Enumerable.Range(0, dt.Columns.Count)
                    .Select(x => new { column = x, count = dt.AsEnumerable().Where(row => row[x] != DBNull.Value).Count() })
                    .ToList();
    
                DataTable dt2 = new DataTable();
                dt2.Columns.Add("Column Name", typeof(string));
                dt2.Columns.Add("Count", typeof(int));
    
                foreach (var count in count1)
                {
                    dt2.Rows.Add(new object[] { dt.Columns[count.column].ColumnName, count.count }); 
                }