Count number of record for specific string in DataGridview row using C# and VB.Net in Windows Forms Application

Last Reply on Jan 23, 2018 02:53 AM By dharmendr

Posted on Jan 22, 2018 11:43 PM
  01-Jan-18 02-Jan-18 03-Jan-18 04-Jan-18 05-Jan-18 06-Jan-18 07-Jan-18 Total Off
Ahemd 1 1   OFF OFF 2 2 2
Ajith 3 3 2 2 1 OFF OFF 2
Soumya OFF 1 1 1 1 1 1 1

I want count how many off in week for each person in the last column in datagridview row vb.net

You are viewing reply posted by: dharmendr on Jan 23, 2018 02:53 AM.
Posted on Jan 23, 2018 02:53 AM

Hi satabeach,

Check this example. Now please take its reference and correct your code.

Form Design

Code

C#

public Form1()
{
    InitializeComponent();
    this.BindGrid();
}

private void Form1_Load(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        int offCount = 0;
        for (int i = 0; i < dataGridView1.Columns.Count; i++)
        {
            if (row.Cells[i].Value.ToString().ToLower() == "off")
            {
                offCount++;
            }
        }
        row.Cells[dataGridView1.Columns.Count - 1].Value = offCount;
    }
}

private void BindGrid()
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[] { 
        new DataColumn("Name"), new DataColumn("01-Jan-18"), new DataColumn("02-Jan-18"),
        new DataColumn("03-Jan-18"), new DataColumn("04-Jan-18"), new DataColumn("05-Jan-18"),
        new DataColumn("06-Jan-18"), new DataColumn("07-Jan-18"), new DataColumn("Total Off")});
    dt.Rows.Add("Ahemd", "1", "1", "OFF", "OFF", "2", "2", "2");
    dt.Rows.Add("Ajith", "3", "3", "2", "2", "1", "OFF", "OFF");
    dt.Rows.Add("Soumya", "OFF", "1", "1", "1", "1", "1", "1");
    dataGridView1.DataSource = dt;
}

VB.Net

Public Sub Form1()
    InitializeComponent()
    Me.BindGrid()
End Sub

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
    For Each row As DataGridViewRow In dataGridView1.Rows
        Dim offCount As Integer = 0
        For i As Integer = 0 To dataGridView1.Columns.Count - 1
            If row.Cells(i).Value.ToString().ToLower() = "off" Then
                offCount += 1
            End If
        Next

        row.Cells(dataGridView1.Columns.Count - 1).Value = offCount
    Next
End Sub

Private Sub BindGrid()
    Dim dt As DataTable = New DataTable()
    dt.Columns.AddRange(New DataColumn() {New DataColumn("Name"), New DataColumn("01-Jan-18"), New DataColumn("02-Jan-18"), New DataColumn("03-Jan-18"), New DataColumn("04-Jan-18"), New DataColumn("05-Jan-18"), New DataColumn("06-Jan-18"), New DataColumn("07-Jan-18"), New DataColumn("Total Off")})
    dt.Rows.Add("Ahemd", "1", "1", "OFF", "OFF", "2", "2", "2")
    dt.Rows.Add("Ajith", "3", "3", "2", "2", "1", "OFF", "OFF")
    dt.Rows.Add("Soumya", "OFF", "1", "1", "1", "1", "1", "1")
    dataGridView1.DataSource = dt
End Sub

Screenshot