Delen via


Procedure: Cellen en kolommen aanpassen in het Besturingselement Windows Forms DataGridView door hun gedrag en uiterlijk uit te breiden

Het besturingselement DataGridView biedt een aantal manieren om het uiterlijk en gedrag ervan aan te passen met behulp van eigenschappen, gebeurtenissen en bijbehorende klassen. Soms hebt u mogelijk vereisten voor uw cellen die verder gaan dan wat deze functies kunnen bieden. U kunt uw eigen aangepaste DataGridViewCell-klasse maken om uitgebreide functionaliteit te bieden.

U maakt een aangepaste DataGridViewCell-klasse door deze te afleiden van de DataGridViewCell basisklasse of een van de afgeleide klassen. Hoewel u elk type cel in elk type kolom kunt weergeven, maakt u doorgaans ook een aangepaste DataGridViewColumn klasse die speciaal is voor het weergeven van uw celtype. Kolomklassen zijn afgeleid van DataGridViewColumn of een van de afgeleide typen.

In het volgende codevoorbeeld maakt u een aangepaste celklasse met de naam DataGridViewRolloverCell die detecteert wanneer de muis binnenkomt en de celgrenzen verlaat. Terwijl de muis binnen de grenzen van de cel valt, wordt een rechthoek in het begin getekend. Dit nieuwe type is afgeleid van DataGridViewTextBoxCell en gedraagt zich in alle andere opzichten als basisklasse. De bijbehorende kolomklasse wordt DataGridViewRolloverColumngenoemd.

Als u deze klassen wilt gebruiken, maakt u een formulier met een besturingselement DataGridView, voegt u een of meer DataGridViewRolloverColumn objecten toe aan de Columns verzameling en vult u het besturingselement in met rijen met waarden.

Opmerking

Dit voorbeeld werkt niet goed als u lege rijen toevoegt. Lege rijen worden bijvoorbeeld gemaakt wanneer u rijen aan het besturingselement toevoegt door de eigenschap RowCount in te stellen. Dit komt doordat de rijen die in dit geval worden toegevoegd, automatisch worden gedeeld, wat betekent dat DataGridViewRolloverCell objecten pas worden geïnstantieerd wanneer u op afzonderlijke cellen klikt, waardoor de bijbehorende rijen niet worden gedeeld.

Omdat voor dit type celaanpassing niet-gedeelde rijen zijn vereist, is het niet geschikt voor gebruik met grote gegevenssets. Zie Aanbevolen procedures voor het schalen van het Besturingselement Windows Forms DataGridViewvoor meer informatie over het delen van rijen.

Opmerking

Wanneer u bent afgeleid van DataGridViewCell of DataGridViewColumn en nieuwe eigenschappen toevoegt aan de afgeleide klasse, moet u de methode Clone overschrijven om de nieuwe eigenschappen te kopiëren tijdens het klonen. U moet ook de Clone methode van de basisklasse aanroepen, zodat de eigenschappen van de basisklasse worden gekopieerd naar de nieuwe cel of kolom.

Het aanpassen van cellen en kolommen in het besturingselement DataGridView

  1. Een nieuwe celklasse, DataGridViewRolloverCellgenoemd, afleiden van het DataGridViewTextBoxCell type.

    public class DataGridViewRolloverCell : DataGridViewTextBoxCell
    {
    
    Public Class DataGridViewRolloverCell
        Inherits DataGridViewTextBoxCell
    
    }
    
    End Class
    
  2. Overschrijf de methode Paint in de klasse DataGridViewRolloverCell. Roep in de overschrijving eerst de implementatie van de basisklasse aan, die de functionaliteit van het gehoste tekstvak afhandelt. Gebruik vervolgens de PointToClient methode van het besturingselement om de cursorpositie (in schermcoördinaten) te transformeren naar de coördinaten van het DataGridView clientgebied. Als de muiscoördinaten binnen de grenzen van de cel vallen, tekent u de insetrechthoek.

    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. Overschrijven de methoden OnMouseEnter en OnMouseLeave in de klasse DataGridViewRolloverCell om cellen te dwingen zichzelf opnieuw te tekenen wanneer de muisaanwijzer binnenkomt of verlaat.

    // 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. Leid een nieuwe klasse af, DataGridViewRolloverCellColumngenoemd, van het DataGridViewColumn type. Wijs in de constructor een nieuw DataGridViewRolloverCell-object toe aan de eigenschap 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
    

Voorbeeld

Het volledige codevoorbeeld bevat een klein testformulier dat het gedrag van het aangepaste celtype laat zien.

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

De code compileren

Voor dit voorbeeld is het volgende vereist:

  • Verwijzingen naar de assembly's System, System.Windows.Forms en System.Drawing.

Zie ook