0

I was previously using a listview and the below would add a row to the listview while settings it's backcolor:

string[] row = { Number, Type, Name };
var listViewItem = new ListViewItem(row);
listViewItem.BackColor = Color.Green;
myListView.Items.Add(listViewItem);

Is there something similar for a grid? At the moment, all I've got is:

string[] row = { Number, Type, Name };
myGrid.Rows.Add(row);

This is note a duplicate: This question is about setting the color of a row at the time of adding it due to a condition not shown on the grid, and not needing to loop through an existing grid and set the color based on a value inside the grid.

Matt
  • 1,490
  • 2
  • 17
  • 41
  • Please have a look here http://stackoverflow.com/questions/15965043/how-to-add-rows-to-datagridview-winforms. – Christos Dec 10 '14 at 22:57
  • @Christos Nice way of adding data to a grid but I don't see where it addressed setting background color? – Matt Dec 10 '14 at 23:02
  • @SteveWellens I'm looking to set the background color when adding a row, that question is iterating through a grid and changing color depending on a condition. – Matt Dec 10 '14 at 23:03

1 Answers1

2

Try this:

string[] row = { Number, Type, Name };
int rowPosition = myGrid.Rows.Add(row);
myGrid.Rows[rowPosition].DefaultCellStyle.BackColor = Color.Red;

The Add method returns the index of the added row and you can use it to set the BackColor property of DefaultCellStyle.

Dean
  • 2,084
  • 17
  • 23
  • Brilliant. Thank-you. The reason why iterating through the array afterwards wouldn't work easily is because the color is set depending on a value that isn't shown in the grid. – Matt Dec 10 '14 at 23:34