namco
namco

Reputation: 6338

Change datagridview cell color by clicking in c#(winform)


I have a datagrid on the form.
and i want to that,
when i click on any cell on any row
the cell back color can change to red color for example.
how can i do that...

Upvotes: 2

Views: 21621

Answers (5)

astyd256
astyd256

Reputation: 11

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.

Upvotes: 1

user2263264
user2263264

Reputation: 21

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.

Upvotes: 2

Cheng
Cheng

Reputation: 31

You can change the DefaultCellStyle. For example:

...
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Red;
...

Upvotes: 3

V4Vendetta
V4Vendetta

Reputation: 38230

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);
     }               
}

Upvotes: 1

Umesh CHILAKA
Umesh CHILAKA

Reputation: 1466

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;

    }

Upvotes: 7

Related Questions