简体   繁体   中英

DataGridView selected cell style

如何更改DataGridView(winforms)上的“选择样式”?

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
            };
        }
        }

使用GridView的SelectedCells属性和DataGridViewCell的Style属性

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;
        } 
    }

You can try the solution provided in this topic . I've tested and approved it.

Hope that helped.

With this you can even draw a colored border to 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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM