开发者

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

开发者 https://www.devze.com 2023-02-11 09:29 出处:网络
I have a datagrid on the form. and i want to that, when i click o开发者_运维技巧n any cell on any row

I have a datagrid on the form.

and i want to that,

when i click o开发者_运维技巧n any cell on any row

the cell back color can change to red color for example.

how can i do that...


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消