DefaultCellStyle Forecolor only applies to one cell

bondra

Well-known member
Joined
Oct 24, 2020
Messages
77
Programming Experience
Beginner
I'm trying to set a color for the DefaulyCellStyle property but in only color the first cell for some reason. Any ideas?

C#:
// Set the selection background color for all the cells.
    dataGridView1.DefaultCellStyle.SelectionBackColor = Color.White;
    dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Black;
DataGridViewCellStyle.ForeColor Property
 
Last edited:
You need to set those properties before you start populating the data grid view.

Also be aware that you are setting the "selection" foreground and background color. In a datagrid view, the default setting is like Excel where the selection is a single cell, at the top left of the sheet. In this case it sounds right that the color is only set for the currently selected cell: the first cell.

The documentation you linked to was ForeColor property, but your code is setting the SelectionForeColor property.
 
Hmm I think I set it beforehand?

C#:
        private void Form1_Load(object sender, EventArgs e)
        {
            dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow;

            Pets.Add(new Cat() { Name = "Missy", Age = 4, FavFood = "Frolic", Breed = "Sheppard", IsHungry = utility.ShuffleProbability()});
            Pets.Add(new Dog() { Name = "Bone", Age = 2, FavFood = "Whiskas", Breed ="Persian", IsHungry = utility.ShuffleProbability()});
            Pets.Add(new Puppy() { Name = "Fido", AgeInMonths = 10, FavFood = "Duck", Breed = "Toller", IsHungry = utility.ShuffleProbability() });

            dataGridView1.DataSource = Pets;
        }
 
If you added columns to the datagridview prior to setting the default cell style, you are populating the data grid view then the style may not apply.

Also, re-read #2. I added quite a bunch of follow-up including the fact that you are reading one set of documentation, but setting a different property than the documentation that you are reading.
 
Don't set properties in code that you can set in the designer. If you want to configure the DefaultCellStyle of the grid then do it in the designer. The only reason to do it in code is if it is changing after the form is created. That doesn't appear to be the case here so why make things harder?
 
Back
Top Bottom