Monday, April 3, 2017

Highlight Duplicate Records in GridView

How to highlight Duplicate Records in GridView.
Hi, today I will share my experience with you which I face long time ago. problem was how to identify if there is any duplicate record. so, after spending too much time on search and finding solution I reached to a solution. below is given a function which finds the duplicate rows in a Gridview without much effort, just we need to pass our Gridview ID and it will find and highlight the duplicate rows. we can find duplicate row depending upon a cell value within a row or for multiple cells also.
Here is the function:

public void HighlightDuplicate(GridView gridview)
    {
        for(int currentRow = 0; currentRow < gridview.Rows.Count - 1; currentRow++)
        {
            GridViewRow rowToCompare = gridview.Rows[currentRow];
            for (int otherRow = currentRow + 1; otherRow < gridview.Rows.Count; otherRow++)
            {
                GridViewRow row = gridview.Rows[otherRow];
                bool duplicateRow = true;
                //check Duplicate on Name Coloumn
                if ((rowToCompare.Cells[2].Text) != (row.Cells[2].Text))
                {
                    duplicateRow = false;
                }
                else if (duplicateRow)
                {
                    rowToCompare.BackColor =System.Drawing.Color.Yellow;
                    row.BackColor = System.Drawing.Color.Yellow;
                }
            }
        }
    }


we will call this function after DataBind() is done to the Gridview.
Call function
HighlightDuplicate(GridView1);

In current function i am checking value of Cell[2] you can set as per your requirements.
This function can also be used for some other operations on the Gridview because you have full control on rows and cell of Gridview even you can find a specific value or control in the Gridview row and do whatever you want.
Comments and Suggestions are Always Welcome!

No comments:

Post a Comment