Nota
O acesso a esta página requer autorização. Podes tentar iniciar sessão ou mudar de diretório.
O acesso a esta página requer autorização. Podes tentar mudar de diretório.
O controle DataGridView fornece várias maneiras de personalizar sua aparência e comportamento usando propriedades, eventos e classes complementares. Ocasionalmente, você pode ter requisitos para suas células que vão além do que esses recursos podem fornecer. Você pode criar sua própria classe DataGridViewCell personalizada para fornecer funcionalidade estendida.
Você cria uma classe DataGridViewCell personalizada derivando da classe base DataGridViewCell ou de uma de suas classes derivadas. Embora possa exibir qualquer tipo de célula em qualquer tipo de coluna, normalmente criará também uma classe DataGridViewColumn personalizada, especializada para exibir o seu tipo de célula. As classes de coluna derivam de DataGridViewColumn ou de um de seus tipos derivados.
No exemplo de código a seguir, você criará uma classe de célula personalizada chamada DataGridViewRolloverCell que deteta quando o mouse entra e sai dos limites da célula. Enquanto o mouse está dentro dos limites da célula, um retângulo embutido é desenhado. Este novo tipo deriva de DataGridViewTextBoxCell e se comporta em todos os outros aspetos como sua classe base. A classe de coluna complementar é chamada DataGridViewRolloverColumn.
Para usar essas classes, crie um formulário contendo um controle DataGridView, adicione um ou mais objetos DataGridViewRolloverColumn à coleção Columns e preencha o controle com linhas contendo valores.
Observação
Este exemplo não funcionará corretamente se você adicionar linhas vazias. Linhas vazias são criadas, por exemplo, quando você adiciona linhas ao controle definindo a propriedade RowCount. Isso ocorre porque as linhas adicionadas nesse caso são compartilhadas automaticamente, o que significa que DataGridViewRolloverCell objetos não são instanciados até que você clique em células individuais, fazendo com que as linhas associadas deixem de ser compartilhadas.
Como esse tipo de personalização de célula requer linhas não compartilhadas, ele não é apropriado para uso com grandes conjuntos de dados. Para obter mais informações sobre a partilha de linhas, consulte Práticas Recomendadas para Dimensionar o Controle DataGridView do Windows Forms.
Observação
Ao derivar de DataGridViewCell ou DataGridViewColumn e adicionar novas propriedades à classe derivada, assegure-se de sobrescrever o método Clone para copiar as novas propriedades durante as operações de clonagem. Você também deve chamar o método Clone da classe base para que as propriedades da classe base sejam copiadas para a nova célula ou coluna.
Para personalizar células e colunas no controle DataGridView
Derive uma nova classe de célula, chamada
DataGridViewRolloverCell, do tipo DataGridViewTextBoxCell.public class DataGridViewRolloverCell : DataGridViewTextBoxCell {Public Class DataGridViewRolloverCell Inherits DataGridViewTextBoxCell}End ClassSubstitua o método Paint na classe
DataGridViewRolloverCell. Na substituição, primeiro chame a implementação da classe base, que lida com a funcionalidade de caixa de texto hospedada. Em seguida, use o método PointToClient do controle para transformar a posição do cursor (em coordenadas da tela) para as coordenadas da área do cliente DataGridView. Se as coordenadas do mouse estiverem dentro dos limites da célula, desenhe o retângulo inserido.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 SubSubstitua os métodos OnMouseEnter e OnMouseLeave na classe
DataGridViewRolloverCellpara forçar as células a se repintarem quando o ponteiro do mouse entrar ou sair delas.// 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 SubDerive uma nova classe, chamada
DataGridViewRolloverCellColumn, do tipo DataGridViewColumn. No construtor, atribua um novo objetoDataGridViewRolloverCellà sua propriedade 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
Exemplo
O exemplo de código completo inclui um pequeno formulário de teste que demonstra o comportamento do tipo de célula personalizado.
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
Compilando o código
Este exemplo requer:
- Referências das assemblies System, System.Windows.Forms e System.Drawing.
Ver também
.NET Desktop feedback