Reputation: 4951
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
Reputation: 5373
There are more than one way to do this:
If you need to change color for entire column:
DGV.Columns[ColumnIndexToColor].DefaultCellStyle.ForeColor = Color.AliceBlue;
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;
}
}
}
}
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
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
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