Bagikan melalui


Cara: Menyesuaikan Sel dan Kolom dalam kontrol Formulir Windows DataGridView dengan Memperluas Perilaku dan Tampilannya

Kontrol ini DataGridView menyediakan sejumlah cara untuk menyesuaikan tampilan dan perilakunya menggunakan properti, peristiwa, dan kelas pendamping. Terkadang, Anda mungkin memiliki persyaratan untuk sel Anda yang melampaui apa yang dapat disediakan fitur-fitur ini. Anda dapat membuat kelas kustom DataGridViewCell Anda sendiri untuk menyediakan fungsionalitas yang diperluas.

Anda membuat kelas kustom DataGridViewCell dengan berasal dari DataGridViewCell kelas dasar atau salah satu kelas turunannya. Meskipun Anda dapat menampilkan semua jenis sel dalam semua jenis kolom, Anda biasanya juga akan membuat kelas kustom DataGridViewColumn khusus untuk menampilkan jenis sel Anda. Kelas kolom berasal dari DataGridViewColumn atau salah satu jenis turunannya.

Dalam contoh kode berikut, Anda akan membuat kelas sel kustom yang disebut DataGridViewRolloverCell yang mendeteksi saat mouse masuk dan meninggalkan batas sel. Saat mouse berada dalam batas sel, persegi panjang inset digambar. Jenis baru ini berasal dari DataGridViewTextBoxCell dan berulah dalam semua hal lain sebagai kelas dasarnya. Kelas kolom pendamping disebut DataGridViewRolloverColumn.

Untuk menggunakan kelas ini, buat formulir yang berisi DataGridView kontrol, tambahkan satu atau beberapa DataGridViewRolloverColumn objek ke Columns koleksi, dan isi kontrol dengan baris yang berisi nilai.

Catatan

Contoh ini tidak akan berfungsi dengan benar jika Anda menambahkan baris kosong. Baris kosong dibuat, misalnya, saat Anda menambahkan baris ke kontrol dengan mengatur RowCount properti . Ini karena baris yang ditambahkan dalam kasus ini dibagikan secara otomatis, yang berarti bahwa DataGridViewRolloverCell objek tidak dibuat sampai Anda mengklik sel individual, sehingga menyebabkan baris terkait menjadi tidak dibagikan.

Karena jenis kustomisasi sel ini memerlukan baris yang tidak dibagikan, tidak sesuai untuk digunakan dengan himpunan data besar. Untuk informasi selengkapnya tentang berbagi baris, lihat Praktik Terbaik untuk Menskalakan Kontrol Formulir Windows DataGridView.

Catatan

Ketika Anda berasal dari DataGridViewCell atau DataGridViewColumn dan menambahkan properti baru ke kelas turunan, pastikan untuk mengambil alih Clone metode untuk menyalin properti baru selama operasi kloning. Anda juga harus memanggil metode kelas Clone dasar sehingga properti kelas dasar disalin ke sel atau kolom baru.

Untuk mengkustomisasi sel dan kolom dalam kontrol DataGridView

  1. Mendapatkan kelas sel baru, yang disebut DataGridViewRolloverCell, dari DataGridViewTextBoxCell jenis .

    public class DataGridViewRolloverCell : DataGridViewTextBoxCell
    {
    
    Public Class DataGridViewRolloverCell
        Inherits DataGridViewTextBoxCell
    
    }
    
    End Class
    
  2. Ambil alih Paint metode di DataGridViewRolloverCell kelas . Dalam penimpaan, pertama-tama panggil implementasi kelas dasar, yang menangani fungsionalitas kotak teks yang dihosting. Kemudian gunakan metode kontrol PointToClient untuk mengubah posisi kursor (dalam koordinat layar) ke DataGridView koordinat area klien. Jika koordinat mouse berada dalam batas sel, gambar persegi panjang inset.

    protected override void Paint(
        Graphics graphics,
        Rectangle clipBounds,
        Rectangle cellBounds,
        int rowIndex,
        DataGridViewElementStates cellState,
        object value,
        object formattedValue,
        string errorText,
        DataGridViewCellStyle cellStyle,
        DataGridViewAdvancedBorderStyle advancedBorderStyle,
        DataGridViewPaintParts paintParts)
    {
        // Call the base class method to paint the default cell appearance.
        base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState,
            value, formattedValue, errorText, cellStyle,
            advancedBorderStyle, paintParts);
    
        // Retrieve the client location of the mouse pointer.
        Point cursorPosition =
            this.DataGridView.PointToClient(Cursor.Position);
    
        // If the mouse pointer is over the current cell, draw a custom border.
        if (cellBounds.Contains(cursorPosition))
        {
            Rectangle newRect = new Rectangle(cellBounds.X + 1,
                cellBounds.Y + 1, cellBounds.Width - 4,
                cellBounds.Height - 4);
            graphics.DrawRectangle(Pens.Red, newRect);
        }
    }
    
    Protected Overrides Sub Paint( _
        ByVal graphics As Graphics, _
        ByVal clipBounds As Rectangle, _
        ByVal cellBounds As Rectangle, _
        ByVal rowIndex As Integer, _
        ByVal elementState As DataGridViewElementStates, _
        ByVal value As Object, _
        ByVal formattedValue As Object, _
        ByVal errorText As String, _
        ByVal cellStyle As DataGridViewCellStyle, _
        ByVal advancedBorderStyle As DataGridViewAdvancedBorderStyle, _
        ByVal paintParts As DataGridViewPaintParts)
    
        ' Call the base class method to paint the default cell appearance.
        MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, _
            value, formattedValue, errorText, cellStyle, _
            advancedBorderStyle, paintParts)
    
        ' Retrieve the client location of the mouse pointer.
        Dim cursorPosition As Point = _
            Me.DataGridView.PointToClient(Cursor.Position)
    
        ' If the mouse pointer is over the current cell, draw a custom border.
        If cellBounds.Contains(cursorPosition) Then
            Dim newRect As New Rectangle(cellBounds.X + 1, _
                cellBounds.Y + 1, cellBounds.Width - 4, _
                cellBounds.Height - 4)
            graphics.DrawRectangle(Pens.Red, newRect)
        End If
    
    End Sub
    
  3. Ambil alih OnMouseEnter metode dan OnMouseLeave di DataGridViewRolloverCell kelas untuk memaksa sel mengecat ulang diri ketika penunjuk mouse masuk atau meninggalkannya.

    // Force the cell to repaint itself when the mouse pointer enters it.
    protected override void OnMouseEnter(int rowIndex)
    {
        this.DataGridView.InvalidateCell(this);
    }
    
    // Force the cell to repaint itself when the mouse pointer leaves it.
    protected override void OnMouseLeave(int rowIndex)
    {
        this.DataGridView.InvalidateCell(this);
    }
    
    ' Force the cell to repaint itself when the mouse pointer enters it.
    Protected Overrides Sub OnMouseEnter(ByVal rowIndex As Integer)
        Me.DataGridView.InvalidateCell(Me)
    End Sub
    
    ' Force the cell to repaint itself when the mouse pointer leaves it.
    Protected Overrides Sub OnMouseLeave(ByVal rowIndex As Integer)
        Me.DataGridView.InvalidateCell(Me)
    End Sub
    
  4. Dapatkan kelas baru, yang disebut DataGridViewRolloverCellColumn, dari DataGridViewColumn jenis . Di konstruktor, tetapkan objek baru DataGridViewRolloverCell ke propertinya CellTemplate .

    public class DataGridViewRolloverCellColumn : DataGridViewColumn
    {
        public DataGridViewRolloverCellColumn()
        {
            this.CellTemplate = new DataGridViewRolloverCell();
        }
    }
    
    Public Class DataGridViewRolloverCellColumn
        Inherits DataGridViewColumn
    
        Public Sub New()
            Me.CellTemplate = New DataGridViewRolloverCell()
        End Sub
    
    End Class
    

Contoh

Contoh kode lengkap mencakup formulir pengujian kecil yang menunjukkan perilaku jenis sel kustom.

using System;
using System.Drawing;
using System.Windows.Forms;

class Form1 : Form
{
    [STAThreadAttribute()]
    public static void Main()
    {
        Application.Run(new Form1());
    }

    public Form1()
    {
        DataGridView dataGridView1 = new DataGridView();
        DataGridViewRolloverCellColumn col =
            new DataGridViewRolloverCellColumn();
        dataGridView1.Columns.Add(col);
        dataGridView1.Rows.Add(new string[] { "" });
        dataGridView1.Rows.Add(new string[] { "" });
        dataGridView1.Rows.Add(new string[] { "" });
        dataGridView1.Rows.Add(new string[] { "" });
        this.Controls.Add(dataGridView1);
        this.Text = "DataGridView rollover-cell demo";
    }
}

public class DataGridViewRolloverCell : DataGridViewTextBoxCell
{
    protected override void Paint(
        Graphics graphics,
        Rectangle clipBounds,
        Rectangle cellBounds,
        int rowIndex,
        DataGridViewElementStates cellState,
        object value,
        object formattedValue,
        string errorText,
        DataGridViewCellStyle cellStyle,
        DataGridViewAdvancedBorderStyle advancedBorderStyle,
        DataGridViewPaintParts paintParts)
    {
        // Call the base class method to paint the default cell appearance.
        base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState,
            value, formattedValue, errorText, cellStyle,
            advancedBorderStyle, paintParts);

        // Retrieve the client location of the mouse pointer.
        Point cursorPosition =
            this.DataGridView.PointToClient(Cursor.Position);

        // If the mouse pointer is over the current cell, draw a custom border.
        if (cellBounds.Contains(cursorPosition))
        {
            Rectangle newRect = new Rectangle(cellBounds.X + 1,
                cellBounds.Y + 1, cellBounds.Width - 4,
                cellBounds.Height - 4);
            graphics.DrawRectangle(Pens.Red, newRect);
        }
    }

    // Force the cell to repaint itself when the mouse pointer enters it.
    protected override void OnMouseEnter(int rowIndex)
    {
        this.DataGridView.InvalidateCell(this);
    }

    // Force the cell to repaint itself when the mouse pointer leaves it.
    protected override void OnMouseLeave(int rowIndex)
    {
        this.DataGridView.InvalidateCell(this);
    }

}

public class DataGridViewRolloverCellColumn : DataGridViewColumn
{
    public DataGridViewRolloverCellColumn()
    {
        this.CellTemplate = new DataGridViewRolloverCell();
    }
}
Imports System.Drawing
Imports System.Windows.Forms

Class Form1
    Inherits Form

    <STAThreadAttribute()> _
    Public Shared Sub Main()
        Application.Run(New Form1())
    End Sub

    Public Sub New()
        Dim dataGridView1 As New DataGridView()
        Dim col As New DataGridViewRolloverCellColumn()
        dataGridView1.Columns.Add(col)
        dataGridView1.Rows.Add(New String() {""})
        dataGridView1.Rows.Add(New String() {""})
        dataGridView1.Rows.Add(New String() {""})
        dataGridView1.Rows.Add(New String() {""})
        Me.Controls.Add(dataGridView1)
        Me.Text = "DataGridView rollover-cell demo"
    End Sub

End Class

Public Class DataGridViewRolloverCell
    Inherits DataGridViewTextBoxCell

    Protected Overrides Sub Paint( _
        ByVal graphics As Graphics, _
        ByVal clipBounds As Rectangle, _
        ByVal cellBounds As Rectangle, _
        ByVal rowIndex As Integer, _
        ByVal elementState As DataGridViewElementStates, _
        ByVal value As Object, _
        ByVal formattedValue As Object, _
        ByVal errorText As String, _
        ByVal cellStyle As DataGridViewCellStyle, _
        ByVal advancedBorderStyle As DataGridViewAdvancedBorderStyle, _
        ByVal paintParts As DataGridViewPaintParts)

        ' Call the base class method to paint the default cell appearance.
        MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, _
            value, formattedValue, errorText, cellStyle, _
            advancedBorderStyle, paintParts)

        ' Retrieve the client location of the mouse pointer.
        Dim cursorPosition As Point = _
            Me.DataGridView.PointToClient(Cursor.Position)

        ' If the mouse pointer is over the current cell, draw a custom border.
        If cellBounds.Contains(cursorPosition) Then
            Dim newRect As New Rectangle(cellBounds.X + 1, _
                cellBounds.Y + 1, cellBounds.Width - 4, _
                cellBounds.Height - 4)
            graphics.DrawRectangle(Pens.Red, newRect)
        End If

    End Sub

    ' Force the cell to repaint itself when the mouse pointer enters it.
    Protected Overrides Sub OnMouseEnter(ByVal rowIndex As Integer)
        Me.DataGridView.InvalidateCell(Me)
    End Sub

    ' Force the cell to repaint itself when the mouse pointer leaves it.
    Protected Overrides Sub OnMouseLeave(ByVal rowIndex As Integer)
        Me.DataGridView.InvalidateCell(Me)
    End Sub

End Class

Public Class DataGridViewRolloverCellColumn
    Inherits DataGridViewColumn

    Public Sub New()
        Me.CellTemplate = New DataGridViewRolloverCell()
    End Sub

End Class

Mengompilasi Kode

Contoh ini membutuhkan:

  • Referensi ke rakitan System, System.Windows.Forms, dan System.Drawing.

Baca juga