Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Set Color for 1 Cell in DataGridView

iam looking for a method to set the color specific only for 1 cell by clicking on it.

I build a Canteen Voter, which you can choice between 4 menues each day.

My DataGridView is connected to a database from which it receives all information and when you click on a cell it is also stored in the database for the logged-in user.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Now I would like to be able to color the cells individually when clicking.

So far I only found the SelectedCells property, but this actually only sets a color for "SelectedCells" when these cells lose focus again they are white again.

I would have liked them to be able to keep this color to make it even clearer to the user which dish he had just chosen.

enter image description here

>Solution :

You should set DataGridViewCell.Style property.

Take a look at this example

private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex < 0 || e.RowIndex == dataGridView1.NewRowIndex)
    {
        return;
    }
    var dataGridViewCellStyle = 
        new DataGridViewCellStyle(dataGridView1.DefaultCellStyle)
    {
        BackColor = Color.Gold
    };
    dataGridView1[e.ColumnIndex, e.RowIndex].Style = dataGridViewCellStyle;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading