DataGridView选择了单元格样式

时间:2009-06-26 17:48:40

标签: c# winforms

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

5 个答案:

答案 0 :(得分:5)

您可以通过为Grid的DefaultCellStyle的SelectedBackColor和SelectedForeColor指定值来轻松更改选定单元格的前景色和背景色。

如果您需要进一步设置样式,则需要处理SelectionChanged事件

编辑:(其他代码示例有错误,调整多个选定的单元格[如在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
            };
        }
        }

答案 1 :(得分:1)

使用GridView的SelectedCells property和DataGridViewCell的Style property

答案 2 :(得分:1)

处理DataGridView上的SelectionChanged事件并添加如下所示的代码:

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

答案 3 :(得分:0)

您可以尝试此topic中提供的解决方案。我已经测试并批准了它。

希望有所帮助。

答案 4 :(得分:0)

使用此功能,您甚至可以为选定的单元格绘制彩色边框。

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