4

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?

3 Answers 3

7

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
    ....
}
2
  • This method would cause that little bit of extra code to run every time a row is repainted. On sufficiently large data sets or on sufficiently slow boxes, the difference may be enough to be noticeable. Probably not an issue, but that is the drawback versus the original solution. Nov 12, 2008 at 20:32
  • Yes, but this is only invoked for the displayed rows, so if the datagrid contains a lot of rows and only a few are displayed, the initial cost of applying format would be lower.
    – Juanma
    Nov 12, 2008 at 21:03
1

I don't really work with WinForms that much, but in ASP you would use the 'ItemDataBound' method. Is there something similar in windows forms for a DataGrid?

If so, in that method, the event arguments would contain the item that was databound, along with the DataGrid row. So the general code would look something like this (syntax is probably off):

if(((MyObject)e.Item.DataItem).Special)
   e.Item.DefaultCellStyle.BackColor = Color.FromArgb(240, 128, 128);
1

I would suggest a few things:

  • look at modifying your rows at _OnRowDatabound
  • Do not set color in your code!!! This would be a big mistake. Use the attributes property and set the cssclass. Wag of the finger to people still doing this.

Let me know if you struggle with the implementation and i'll post a snippet.

1
  • Do not set color in your code? Where you want me to color the line if it's not in the form (The View)... Nov 12, 2008 at 23:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.