简体   繁体   中英

C# DataGridView Highlight Row

DataGridView.. my focus on first column. On the highlight rows with same values. 突出显示具有相同值的行。
Let's say rows with 1's highlight with red, rows with 3's highlight with blue, 5's with green..
or 1's with red, no highlight for 3's, 5's with red again (like alternative color).

Idea is to visually separate rows with the same values.

Any ideas guys? Thanks in advance.

Column1 | 
------
1 
1     
3
3
3      
5 
5   

Tried , but can't figure visual separation:

int i, i_temp = 0;
foreach (DataGridViewRow dr in dgv.Rows)
        {
            i = int.Parse(dr.Cells["Column1"].Value.ToString());
            if (i_temp == int.Parse(dr.Cells["Column1"].Value.ToString()))
            {
                dr.DefaultCellStyle.BackColor = Color.Red;
                i_temp = i;
            }  
        }

The prescribed way to do this is in the CellFormatting event.

private void MyGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    var dr = MyGrid.Rows[e.RowIndex];
    var intVal = int.Parse(dr.Cells["Column1"].Value.ToString());
    switch (intVal)
    {
        case 1:
            e.CellStyle.BackColor = Color.Red;
            break;
        case 3:
            e.CellStyle.BackColor = Color.Blue;
            break;
        case 5:
            e.CellStyle.BackColor = Color.Green;
            break;
        default:
            break;
    }
}

Note that you can apply this to certain columns only by making the formatting conditional on the e.ColumnIndex property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM