Instrukcje: dostosowywanie komórek i kolumn w kontrolce DataGridView (Formularze systemu Windows) przez rozszerzanie ich zachowania i wyglądu

Kontrolka DataGridView udostępnia wiele sposobów dostosowywania jej wyglądu i zachowania przy użyciu właściwości, zdarzeń i klas towarzyszących. Czasami mogą wystąpić wymagania dotyczące komórek, które wykraczają poza to, co te funkcje mogą zapewnić. Możesz utworzyć własną klasę niestandardową, DataGridViewCell aby zapewnić rozszerzone funkcje.

Klasę niestandardową DataGridViewCell tworzy się, wyprowadzając z DataGridViewCell klasy bazowej lub jednej z jej klas pochodnych. Mimo że można wyświetlić dowolny typ komórki w dowolnym typie kolumny, DataGridViewColumn zazwyczaj tworzy się również niestandardową klasę wyspecjalizowaną do wyświetlania typu komórki. Klasy kolumn pochodzą od lub DataGridViewColumn jednego z jej typów pochodnych.

W poniższym przykładzie kodu utworzysz niestandardową DataGridViewRolloverCell klasę komórek o nazwie , która wykrywa, kiedy mysz wchodzi i opuszcza granice komórki. Gdy mysz znajduje się w granicach komórki, rysowany jest prostokąt inset. Ten nowy typ pochodzi od klasy DataGridViewTextBoxCell bazowej i zachowuje się we wszystkich innych aspektach. Klasa kolumny towarzyszącej nosi nazwę DataGridViewRolloverColumn.

Aby użyć tych klas, utwórz DataGridView formularz zawierający kontrolkę, DataGridViewRolloverColumnColumns dodaj co najmniej jeden obiekt do kolekcji i wypełnij kontrolkę wierszami zawierającymi wartości.

Uwaga

Ten przykład nie będzie działać poprawnie, jeśli dodasz puste wiersze. Puste wiersze są tworzone na przykład podczas dodawania wierszy do kontrolki przez ustawienie właściwości RowCount . Jest to spowodowane tym, że wiersze dodane w tym przypadku są automatycznie udostępniane, co oznacza, DataGridViewRolloverCell że obiekty nie są tworzone, dopóki nie klikniesz poszczególnych komórek, co spowoduje, że skojarzone wiersze staną się nieudostępnione.

Ponieważ ten typ dostosowania komórki wymaga wierszy nieudostępnionych, nie jest odpowiedni do użytku z dużymi zestawami danych. Aby uzyskać więcej informacji na temat udostępniania wierszy, zobacz Best Practices for Scaling the Windows Forms DataGridView Control (Najlepsze rozwiązania dotyczące skalowania kontrolki DataGridView).

Uwaga

W przypadku dodawania DataGridViewCellDataGridViewColumnClone nowych właściwości do klasy pochodnej lub należy zastąpić metodę w celu skopiowania nowych właściwości podczas operacji klonowania. Należy również wywołać metodę Clone klasy bazowej, aby właściwości klasy bazowej zostały skopiowane do nowej komórki lub kolumny.

Aby dostosować komórki i kolumny w kontrolce DataGridView

  1. Wyprowadzanie nowej klasy komórki o nazwie DataGridViewRolloverCellz DataGridViewTextBoxCell typu .

    public class DataGridViewRolloverCell : DataGridViewTextBoxCell
    {
    
    Public Class DataGridViewRolloverCell
        Inherits DataGridViewTextBoxCell
    
    }
    
    End Class
    
  2. Zastąp metodę Paint w DataGridViewRolloverCell klasie . W przesłonięcie najpierw wywołaj implementację klasy bazowej, która obsługuje funkcję hostowanych pól tekstowych. Następnie użyj metody kontrolki PointToClient , aby przekształcić położenie kursora (we współrzędnych ekranu) na DataGridView współrzędne obszaru klienta. Jeśli współrzędne myszy należą do granic komórki, narysuj prostokąt 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. Przesłoń OnMouseEnter metody i OnMouseLeave w DataGridViewRolloverCell klasie , aby wymusić, aby komórki się odwzajemniły, gdy wskaźnik myszy wchodzi lub opuszcza je.

    // 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. Wyprowadzanie nowej klasy o nazwie DataGridViewRolloverCellColumnz DataGridViewColumn typu . W konstruktorze przypisz nowy obiekt DataGridViewRolloverCell do jego CellTemplate właściwości.

    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
    

Przykład

Kompletny przykład kodu zawiera mały formularz testowy, który demonstruje zachowanie niestandardowego typu komórki.

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

Kompilowanie kodu

Ten przykład wymaga:

  • Odwołania do systemu, system. Windows. Formularze i zestawy System.Drawing.

Zobacz też