Различные цветные линии в DataGridView (DGV) - PullRequest
0 голосов
/ 06 октября 2011

У меня есть представление таблицы данных, и мне интересно, можно ли выделить только определенные строки, содержащие определенное значение столбца.

Так что я бы хотел, чтобы все строки по умолчанию были черными с белым текстом, кроме любой строки, у которой есть указанный столбец, равный FUJI/UNIVERSAL. Для этой строки я бы хотел, чтобы она была желтой с черным текстом.

Так что мой вопрос ... это возможно? и если да, то как?

Ответы [ 3 ]

2 голосов
/ 06 октября 2011

Лучшее место - это событие RowPrePaint объекта DataGridView.

Вот как вы можете этого достичь.

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 голос
/ 06 октября 2011

Например, обработав событие 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;

    }
1 голос
/ 06 октября 2011

Обработка события OnPaint для элемента управления DataGridView.

Разбор строк и установка цвета для строк, содержащих искомую информацию.

Пример кода:

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

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...