Saturday, March 12, 2016

DataGridview check for duplicate values and group code in separate column

Hi, I've always been a desktop developer ever since Visual Basic 6.0 came into existence. While I'm busy doing projects for the web platform, I always go back to my roots of solving desktop issues in .NET. :-D

Well, going back to the issue, a certain member in Visual Basic forums posted an issue on how to check duplicate values in a particular datagridview column with DateTime as type. Once a duplicate value has been detected, the code number will be grouped in another datagridview column with label total. See sample screenshot for the desired output:
After creating the logic, I proceed to converting it to code.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
private void SpotDuplicates()
{
    int i = 0;
    int j = 0;
 
    for (i = 0; i <= dgvDates.RowCount - 1; i++)
    {
        for (j = 0; j <= dgvDates.RowCount - 1; j++)
        {
            if (i > j)
            {
                if (Convert.ToDateTime(dgvDates[0, i].Value) == Convert.ToDateTime(dgvDates[0, j].Value))
                    dgvDates[3, i].Value += String.Format(" {0}", dgvDates[1, j].Value.ToString());
            }
            if (i < j)
            {
                if (Convert.ToDateTime(dgvDates[0, i].Value) == Convert.ToDateTime(dgvDates[0, j].Value))
                    dgvDates[3, i].Value += String.Format(" {0}", dgvDates[1, j].Value.ToString());
            }
            if (i == j)
            {
                if(!dgvDates.Rows[i].IsNewRow)
                    dgvDates[3, i].Value += String.Format(" {0}", dgvDates[1, i].Value.ToString());
            }
        }
    }
}
The method will be called after binding the collection to the datagridview's itemsource property. :-)

0 comments:

Post a Comment