Search code examples
c#winformsdatagridviewdatagridviewcolumn

How can I fake an "AlternatingColumnsDefaultCellStyle" for the DataGridView?


DataGridView has an "AlternatingRowsDefaultCellStyle," which works like a champ. But I need the opposite sort of demarcation/decoration. Is there a property that can get the column backgrounds to be a different color than the default, or do I need to write code for the CellFormatting event, or...?

UPDATE

OK, this seems odd:

With this code, from Ascension:

dataGridView1.Columns[i].ItemStyle.BackColor = Color.Blue;

...I get:

'System.Windows.Forms.DataGridViewColumn' does not contain a definition for 'ItemStyle' and no extension method 'ItemStyle' accepting a first argument of type 'System.Windows.Forms.DataGridViewColumn' could be found (are you missing a using directive or an assembly reference?)

However, if I enter just the first part (dataGridView1.Columns[i].), I DO get "ItemStyle" via Intellisense as a valid option to select, but then it turns red when I do (possibly a Resharper effect). A dot after that allows the BackColor property to be selected, which is then NOT red.

Why is this bizarre behavior occurring, and is there a workaround?

And: Do red Intellisense items indicate inaccessibility, and if so, why are they displayed? Are "teaser" members of any value?

UPDATE 2

This works (inspired by Ascension, so I'm giving him/her the correct answer):

DataGridViewCell cell = new DataGridViewTextBoxCell();
cell.Style.BackColor = Color.Wheat;
dataGridView1.Columns[i].CellTemplate = cell;

Solution

  • Try this:

    DataGridView Property -> Misc -> Columns ... -> ItemStyle -> BackColor
    

    or the script below

    protected void Page_Load(object sender, EventArgs e)
            {
                for (int i = 0; i < GridView1.Columns.Count; i++)
                {
                    if (i % 2 == 0)
                    {
                        GridView1.Columns[i].ItemStyle.BackColor = Color.Red;
                    }
                    else
                    {
                        GridView1.Columns[i].ItemStyle.BackColor = Color.Blue; ;
                    }
                }
            }