출처: https://stackoverrun.com/ko/q/6586360


Gridview의 데이터 중 중복 데이터를 찾아서 표시해준다.

 if (int.Parse(rowToCompare.Cells[0].Text) != int.Parse(row.Cells[0].Text)) 

첫번째 값만 비교.


코드는 다음과 같다.

using System.Data;
using System.Drawing; 


protected void bind()

    con.Open(); 
    SqlCommand cmd = con.CreateCommand(); 
    cmd.CommandType = CommandType.Text; 
    cmd.CommandText = "select * from tblSample"; 
    SqlDataAdapter da = new SqlDataAdapter(cmd); 

    DataSet ds = new DataSet(); 
    da.Fill(ds); 
    GridView1.DataSource = ds; 
    GridView1.DataBind(); 

    HighlightDuplicate(this.GridView1); 

    con.Close(); 

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; 

            if (int.Parse(rowToCompare.Cells[0].Text) != int.Parse(row.Cells[0].Text))
            {
                duplicateRow = false;
            }
            else if (duplicateRow)
            {
                rowToCompare.BackColor = Color.Red;
                row.BackColor = Color.Red;
            } 

         } 

    } 

 } 

Posted by 노을지기