DataGridView(DGV)中的不同彩色线条

时间:2011-10-06 17:32:22

标签: c# datagridview row match

我有一个数据网格视图,我想知道是否可以仅突出显示包含特定列值的某些行。

所以我希望所有行都默认为带有白色文本的黑色,除了指定列等于 FUJI/UNIVERSAL 的任何行。对于这一行,我希望它是黄色的黑色文本。

所以我的问题是......这可能吗?如果是的话,怎么样?

3 个答案:

答案 0 :(得分:2)

最佳位置是DataGridView的RowPrePaint事件。

以下是如何实现这一目标。

void dataGridView1_RowPrePaint(object sender,
        DataGridViewRowPrePaintEventArgs e)
{
    if (dataGridView1.Rows[e.RowIndex].Cells[0].Value == "YourConditionalValue")
    {
        dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow;
    }
}

答案 1 :(得分:1)

处理DataGridView控件的OnPaint事件。

解析行,并在包含您要查找的信息的行上设置颜色。

一些示例代码:

int specificColumnIndex = 5;
const string FUJIUNIV = "FUJI/UNIVERSAL";
const Color cFUJIBACK = Color.Yellow;
const Color cFUJITEXT = Color.Black;

public Form1() {
  InitializeComponent();
  dataGridView1.Paint += new PaintEventHandler(DataGridView_Paint);
}

private void DataGridView_Paint(object sender, PaintEventArgs e) {
  foreach (DataGridViewRow row in dataGridView1.Rows) {
    if (row.Cells[specificColumnIndex].Value.ToString() == FUJIUNIV) {
      foreach (DataGridViewCell cell in row.Cells) {
        cell.Style.BackColor = cFUJIBACK;
        cell.Style.ForeColor = cFUJITEXT;
        cell.Style.SelectionBackColor = Color.Gold;
      }
    }
  }
}

}

答案 2 :(得分:1)

例如,通过处理OnCellFormatting事件。

这是我的一个旧的WinForms爱好项目的一段实际代码,它正是这样做的。它还告诉我评论的重要性(我现在还没有机会记住它)。

我相信你可以根据自己的目的调整它。

    private void sheetCalendar_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (CurrentRota == null)
        {
            return;
        }
        /* A word of explanation is needed. We retrieve the DataGridView from sender
         * and we access the cell in question directly. 
         * MSDN advices against it -
         * "to avoid performance penalties When handling this event,
         * access the cell through the parameters of the event handler
         * rather than accessing the cell directly."
         * 
         * The problem is that we don't want to set the same colour to the same cell
         * over and over again.
         * And e.CellStyle always "forgets" what colour the call had had! */
        var dgrid = sender as DataGridView;
        var _col = e.ColumnIndex; 
        var _row = e.RowIndex; 
        var _highlight = (((Rota) sheetCalendar.Rows[e.RowIndex].DataBoundItem).Monday ==
                          CurrentRota.Monday);
        var color = _highlight ?
                                   Settings.Default.DGRIDCalendar_CurrentlyEditedBackColor :
                                                                                               SystemColors.Window;
        if (dgrid[_col, _row].Style.BackColor != color)
            dgrid[_col, _row].Style.BackColor = color;

    }
相关问题