tags:

views:

1697

answers:

3

How can I change the "selection style" on a DataGridView (winforms)?

+1  A: 

Use the SelectedCells property of the GridView and the Style property of the DataGridViewCell.

Matthew Jones
no good. Tested with a DataGridView on an empty form using this code (only changes the first selected cell):private void dataGridView1_SelectionChanged(object sender, EventArgs e){ dataGridView1.SelectedCells[0].Style.BackColor = Color.Beige;}The style is only visible after the selection is changed to another cell.
Yanko Hernández Alvarez
A: 

Handle the SelectionChanged event on your DataGridView and add code that looks something like this:

    private void dataGridView1_SelectionChanged(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in this.dataGridView1.Rows)
        {
            foreach (DataGridViewCell c in row.Cells)
            {
                c.Style = this.dataGridView1.DefaultCellStyle;
            }
        }


        DataGridViewCellStyle style = new DataGridViewCellStyle();
        style.BackColor = Color.Red;
        style.Font = new Font("Courier New", 14.4f, FontStyle.Bold);
        foreach (DataGridViewCell cell in this.dataGridView1.SelectedCells)
        {
            cell.Style = style;
        } 
    }
BFree
Tested. Incomplete. The background isn't applied, while the font is. Weird
Yanko Hernández Alvarez
The background IS applies, but the color of the "Selection" is overriding it. If you double click in the cell to edit, you'll see the background color.
BFree
A: 

You can easily change the forecolor and backcolor of selcted cells by assigning values to the SelectedBackColor and SelectedForeColor of the Grid's DefaultCellStyle.

If you need to do any further styling you you need to handle the SelectionChanged event

Edit: (Other code sample had errors, adjusting for multiple selected cells [as in fullrowselect])

using System.Drawing.Font;

private void dataGridView_SelectionChanged(object sender, EventArgs e)
     {

      foreach(DataGridViewCell cell in ((DataGridView)sender).SelectedCells)
  {
   cell.Style = new DataGridViewCellStyle()
   {
    BackColor = Color.White,
    Font = new Font("Tahoma", 8F),
    ForeColor = SystemColors.WindowText,
    SelectionBackColor = Color.Red,
    SelectionForeColor = SystemColors.HighlightText
   };
  }
     }
Luis
SelectedBackColor, SelectedForeColor OK. It seems there is no way to set different colors for differents cells. :-(
Yanko Hernández Alvarez
SelectedBackColor and SelectedForeColor when used on the DefaultCellStyle property will apply the same colors to any selected cell. If you want to set a style to different cells, once again the answer is to handle the SelectionChanged event and do some conditional assignment based on the row or the column of the selected cell.
Luis
Thanks!!!! exactly what I was looking for... It's a shame I cant vote yet!!!
Yanko Hernández Alvarez