user2214609
user2214609

Reputation: 4951

Changed datagridview cell backgroung color

I try: dataGridView.Rows[0].Cells[4].Style.BackColor = Color.AliceBlue; and it works fine but in case i am add item to my datagridview i don't know which Row number i am working with.

this is how i am adding items to my datagridview:

    public void addToDataGridView()
    {
        dataGridView.Rows.Add( "test1", fileName, fileSize, DateTime.Now, "myStatus");
    }

Upvotes: 2

Views: 429

Answers (3)

Arie
Arie

Reputation: 5373

There are more than one way to do this:

  1. If you need to change color for entire column:

    DGV.Columns[ColumnIndexToColor].DefaultCellStyle.ForeColor = Color.AliceBlue;
    
  2. If you need to change color based on some condition and your DGV is bound, you can use DataBindingComplete event

    private void DGV_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
      if(DGV.Rows.Count>0 && DGV.Columns.Count>0)
      {
        foreach (DataGridViewRow r in DGV.Rows)
        {
          if(condition)
          {
            DataGridViewCheckBoxCell cell = r.Cells[ColumnIndexToColor];
            cell.Style.BackColor = Color.AliceBlue;
          }
        }
      }
    }
    
  3. If you need to change color based on some condition and your DGV is not bound: when you add row to DGV as in answer by @Chris

Upvotes: 1

Jaroslav Kadlec
Jaroslav Kadlec

Reputation: 2543

if you are using dataGridView.Rows.Add(), you are adding row to end of dgw => its index will be dataGridView.Rows.Count - 1

EDIT:
Solution of Chris is much better than using dataGridView.Rows.Count - 1

You can choose other solution - you create DataGridViewRow in which you can set style etc. and then simply add it to dgw.

Upvotes: 0

Chris
Chris

Reputation: 8647

The dataGridView.Rows.Add method gives you the index of the added row.

public void addToDataGridView()
{
    int index = dataGridView.Rows.Add("test1", fileName, fileSize, DateTime.Now, "myStatus");
    dataGridView.Rows(index).Cells(4).Style.BackColor = Color.AliceBlue;
}

Upvotes: 2

Related Questions