Show / Hide Table of Contents

Практическое руководство. Настройка внешнего вида ячеек элемента управления DataGridView в Windows Forms

Можно настроить внешний вид ячеек, обработка DataGridView элемента управления CellPainting событий. Можно извлечь DataGridView элемента управления Graphics из Graphics свойство DataGridViewCellPaintingEventArgs. С этим Graphics, могут повлиять на внешний вид всего DataGridView элемента управления, но будет обычно требуется изменить только на внешний вид ячейки, окрашиваемого в данный момент. ClipBounds Свойство DataGridViewCellPaintingEventArgs позволяет ограничить применение операций рисования к ячейке, окрашиваемого в данный момент.

В следующем примере кода будет рисовать все ячейки в ContactName столбца с помощью DataGridView цветовую схему для элемента управления. Текстовое содержимое каждой ячейки, рисуется в Crimson, и в тот же цвет, что рисуется внутренняя рамка DataGridView элемента управления GridColor свойство.

Пример

private void dataGridView1_CellPainting(object sender,
System.Windows.Forms.DataGridViewCellPaintingEventArgs e)
{
    if (this.dataGridView1.Columns["ContactName"].Index ==
        e.ColumnIndex && e.RowIndex >= 0)
    {
        Rectangle newRect = new Rectangle(e.CellBounds.X + 1,
            e.CellBounds.Y + 1, e.CellBounds.Width - 4,
            e.CellBounds.Height - 4);

        using (
            Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor),
            backColorBrush = new SolidBrush(e.CellStyle.BackColor))
        {
            using (Pen gridLinePen = new Pen(gridBrush))
            {
                // Erase the cell.
                e.Graphics.FillRectangle(backColorBrush, e.CellBounds);

                // Draw the grid lines (only the right and bottom lines;
                // DataGridView takes care of the others).
                e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,
                    e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,
                    e.CellBounds.Bottom - 1);
                e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,
                    e.CellBounds.Top, e.CellBounds.Right - 1,
                    e.CellBounds.Bottom);

                // Draw the inset highlight box.
                e.Graphics.DrawRectangle(Pens.Blue, newRect);

                // Draw the text content of the cell, ignoring alignment.
                if (e.Value != null)
                {
                    e.Graphics.DrawString((String)e.Value, e.CellStyle.Font,
                        Brushes.Crimson, e.CellBounds.X + 2,
                        e.CellBounds.Y + 2, StringFormat.GenericDefault);
                }
                e.Handled = true;
            }
        }
    }
}

Компиляция кода

Для этого примера требуются:

  • Объект DataGridView управления с именем dataGridView1 с ContactName столбца, как показано в таблице Customers в базе данных Northwind.

  • ссылки на сборки System, System.Windows.Forms и System.Drawing.

См. также

  • DataGridView
  • CellPainting
  • Настройка элементов управления DataGridView в Windows Forms
Back to top Неофициальная документация по .NET на русском языке. Лицензия: CC-BY 4.0. Основано на документации по .NET с Microsoft Docs
Generated by DocFX