use cell click event
in the event just assign cell.backcolor to color.red
private void GridView_CellClick(object sender, DataGridViewCellEventArgs e)
private void GridView_CellClick(object sender, DataGridViewCellEventArgs e){
DataGridViewCellStyle CellStyle = new DataGridViewCellStyle();
CellStyle.BackColor = Color.Red;
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style = CellStyle;
}
You can change the DefaultCellStyle. For example:
...
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Red;
...
DataGridViewCell cell;
cell = datagridview1[0,0]; // location of cell
cell.Style.BackColor = Color.LimeGreen; // or whatever color you want
This could be placed in a loop etc., using the indices.
I would recommend setting it in the Cell_Enter event
OR
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.Value != null)
{
if (condition)
e.CellStyle.BackColor = Color.FromArgb(255, 160, 160);
}
}
Update from 2022, working with Visual Studio 2022, to the right answer of the user @Umesh CHILAKA.
DataGridViewCellStyle has BackColor property, meaning you can access this directly, so you can consider to use the following, as it will work too:
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Red
Another plus of this aproach is that you don't create another object DataGridViewCellStyle.
精彩评论