Search code examples
c#.netwinforms.net-2.0c#-2.0

(DataGridView + Binding)How to color line depending of the object binded?


I would like to add a backcolor for specific line depending of a Property of the object binded.

The solution I have (and it works) is to use the Event DataBindingComplete but I do not think it's the best solution.

Here is the event:

    private void myGrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {

        for (int i = 0; i < this.myGrid.Rows.Count; i++)
        {
            if((this.myGrid.Rows[i].DataBoundItem as MyObject).Special)
            {
                this.myGrid.Rows[i].DefaultCellStyle.BackColor = Color.FromArgb(240, 128, 128);
            }
        }
    }

Any other option that would be better?


Solution

  • You can also attach an event handler to RowPostPaint:

    dataGridView1.RowPostPaint += OnRowPostPaint;
    
    void OnRowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
    {
        MyObject value = (MyObject) dataGridView1.Rows[e.RowIndex].DataBoundItem;
        DataGridViewCellStyle style = dataGridView1.Rows[e.RowIndex].DefaultCellStyle;
    
        // Do whatever you want with style and value
        ....
    }