DataGridView selected cell style

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

+4
source share
5 answers

You can easily change the colors of forecolor and backcolor selcted cells by assigning the values ​​of SelectedBackColor and SelectedForeColor to the DefaultCellStyle grid.

If you need to do another style, you need to handle the SelectionChanged event

Edit: (Another sample code had errors, setting for several selected cells [as in full view]]

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 }; } } 
+5
source

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

+1
source

Handle the SelectionChanged event in 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; } } 
+1
source

You can try the solution presented in this thread . I tested and approved it.

Hope this helps.

0
source

In this case, you can even draw a colored frame for the selected cells.

 private void dataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.RowIndex >= 0 && e.ColumnIndex >= 0) { if (dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected == true) { e.Paint(e.CellBounds, DataGridViewPaintParts.All & ~DataGridViewPaintParts.Border); using (Pen p = new Pen(Color.Red, 1)) { Rectangle rect = e.CellBounds; rect.Width -= 2; rect.Height -= 2; e.Graphics.DrawRectangle(p, rect); } e.Handled = true; } } } 
0
source

All Articles