DataGridColumnStyle Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Especifica a aparência, formatação do texto e comportamento de uma DataGrid coluna de controlo. Esta aula é abstrata.
public ref class DataGridColumnStyle abstract : System::ComponentModel::Component, System::Windows::Forms::IDataGridColumnStyleEditingNotificationService
public abstract class DataGridColumnStyle : System.ComponentModel.Component, System.Windows.Forms.IDataGridColumnStyleEditingNotificationService
type DataGridColumnStyle = class
inherit Component
interface IDataGridColumnStyleEditingNotificationService
Public MustInherit Class DataGridColumnStyle
Inherits Component
Implements IDataGridColumnStyleEditingNotificationService
- Herança
- Derivado
- Implementações
Exemplos
O seguinte exemplo de código cria um DataGridColumnStyle que hospeda um DateTimePicker controlo.
#using <System.dll>
#using <System.Data.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>
#using <System.Xml.dll>
using namespace System;
using namespace System::Data;
using namespace System::Windows::Forms;
using namespace System::Drawing;
using namespace System::Security::Permissions;
// This example shows how to create your own column style that
// hosts a control, in this case, a DateTimePicker.
public ref class CustomDateTimePicker : public DateTimePicker
{
protected:
[SecurityPermission(SecurityAction::Demand, Flags=SecurityPermissionFlag::UnmanagedCode)]
virtual bool ProcessKeyMessage( Message% m ) override
{
// Keep all the keys for the DateTimePicker.
return ProcessKeyEventArgs( m );
}
};
public ref class DataGridTimePickerColumn : public DataGridColumnStyle
{
private:
CustomDateTimePicker^ customDateTimePicker1;
// The isEditing field tracks whether or not the user is
// editing data with the hosted control.
bool isEditing;
public:
DataGridTimePickerColumn()
{
customDateTimePicker1 = gcnew CustomDateTimePicker;
customDateTimePicker1->Visible = false;
}
protected:
virtual void Abort( int /*rowNum*/ ) override
{
isEditing = false;
customDateTimePicker1->ValueChanged -=
gcnew EventHandler( this, &DataGridTimePickerColumn::TimePickerValueChanged );
Invalidate();
}
virtual bool Commit( CurrencyManager^ dataSource, int rowNum ) override
{
customDateTimePicker1->Bounds = Rectangle::Empty;
customDateTimePicker1->ValueChanged -=
gcnew EventHandler( this, &DataGridTimePickerColumn::TimePickerValueChanged );
if ( !isEditing )
return true;
isEditing = false;
try
{
DateTime value = customDateTimePicker1->Value;
SetColumnValueAtRow( dataSource, rowNum, value );
}
catch ( Exception^ )
{
Abort( rowNum );
return false;
}
Invalidate();
return true;
}
virtual void Edit(
CurrencyManager^ source,
int rowNum,
Rectangle bounds,
bool /*readOnly*/,
String^ /*displayText*/,
bool cellIsVisible ) override
{
DateTime value = (DateTime)
GetColumnValueAtRow( source, rowNum );
if ( cellIsVisible )
{
customDateTimePicker1->Bounds = Rectangle(
bounds.X + 2, bounds.Y + 2,
bounds.Width - 4, bounds.Height - 4 );
customDateTimePicker1->Value = value;
customDateTimePicker1->Visible = true;
customDateTimePicker1->ValueChanged +=
gcnew EventHandler( this, &DataGridTimePickerColumn::TimePickerValueChanged );
}
else
{
customDateTimePicker1->Value = value;
customDateTimePicker1->Visible = false;
}
if ( customDateTimePicker1->Visible )
DataGridTableStyle->DataGrid->Invalidate( bounds );
customDateTimePicker1->Focus();
}
virtual System::Drawing::Size GetPreferredSize(
Graphics^ /*g*/,
Object^ /*value*/ ) override
{
return Size( 100, customDateTimePicker1->PreferredHeight + 4);
}
virtual int GetMinimumHeight() override
{
return customDateTimePicker1->PreferredHeight + 4;
}
virtual int GetPreferredHeight( Graphics^ /*g*/,
Object^ /*value*/ ) override
{
return customDateTimePicker1->PreferredHeight + 4;
}
virtual void Paint( Graphics^ g,
Rectangle bounds,
CurrencyManager^ source,
int rowNum ) override
{
Paint( g, bounds, source, rowNum, false );
}
virtual void Paint(
Graphics^ g,
Rectangle bounds,
CurrencyManager^ source,
int rowNum,
bool alignToRight ) override
{
Paint(
g, bounds,
source,
rowNum,
Brushes::Red,
Brushes::Blue,
alignToRight );
}
virtual void Paint(
Graphics^ g,
Rectangle bounds,
CurrencyManager^ source,
int rowNum,
Brush^ backBrush,
Brush^ foreBrush,
bool /*alignToRight*/ ) override
{
DateTime date = (DateTime)
GetColumnValueAtRow( source, rowNum );
Rectangle rect = bounds;
g->FillRectangle( backBrush, rect );
rect.Offset( 0, 2 );
rect.Height -= 2;
g->DrawString( date.ToString( "d" ),
this->DataGridTableStyle->DataGrid->Font,
foreBrush, rect );
}
virtual void SetDataGridInColumn( DataGrid^ value ) override
{
DataGridColumnStyle::SetDataGridInColumn( value );
if ( customDateTimePicker1->Parent != nullptr )
{
customDateTimePicker1->Parent->Controls->Remove
( customDateTimePicker1 );
}
if ( value != nullptr )
{
value->Controls->Add( customDateTimePicker1 );
}
}
private:
void TimePickerValueChanged( Object^ /*sender*/, EventArgs^ /*e*/ )
{
// Remove the handler to prevent it from being called twice in a row.
customDateTimePicker1->ValueChanged -=
gcnew EventHandler( this, &DataGridTimePickerColumn::TimePickerValueChanged );
this->isEditing = true;
DataGridColumnStyle::ColumnStartedEditing( customDateTimePicker1 );
}
};
public ref class MyForm: public Form
{
private:
DataTable^ namesDataTable;
DataGrid^ grid;
public:
MyForm()
{
grid = gcnew DataGrid;
InitForm();
namesDataTable = gcnew DataTable( "NamesTable" );
namesDataTable->Columns->Add( gcnew DataColumn( "Name" ) );
DataColumn^ dateColumn = gcnew DataColumn
( "Date",DateTime::typeid );
dateColumn->DefaultValue = DateTime::Today;
namesDataTable->Columns->Add( dateColumn );
DataSet^ namesDataSet = gcnew DataSet;
namesDataSet->Tables->Add( namesDataTable );
grid->DataSource = namesDataSet;
grid->DataMember = "NamesTable";
AddGridStyle();
AddData();
}
private:
void AddGridStyle()
{
DataGridTableStyle^ myGridStyle = gcnew DataGridTableStyle;
myGridStyle->MappingName = "NamesTable";
DataGridTextBoxColumn^ nameColumnStyle =
gcnew DataGridTextBoxColumn;
nameColumnStyle->MappingName = "Name";
nameColumnStyle->HeaderText = "Name";
myGridStyle->GridColumnStyles->Add( nameColumnStyle );
DataGridTimePickerColumn^ timePickerColumnStyle =
gcnew DataGridTimePickerColumn;
timePickerColumnStyle->MappingName = "Date";
timePickerColumnStyle->HeaderText = "Date";
timePickerColumnStyle->Width = 100;
myGridStyle->GridColumnStyles->Add( timePickerColumnStyle );
grid->TableStyles->Add( myGridStyle );
}
void AddData()
{
DataRow^ dRow = namesDataTable->NewRow();
dRow->default[ "Name" ] = "Name 1";
dRow->default[ "Date" ] = DateTime(2001,12,01);
namesDataTable->Rows->Add( dRow );
dRow = namesDataTable->NewRow();
dRow->default[ "Name" ] = "Name 2";
dRow->default[ "Date" ] = DateTime(2001,12,04);
namesDataTable->Rows->Add( dRow );
dRow = namesDataTable->NewRow();
dRow->default[ "Name" ] = "Name 3";
dRow->default[ "Date" ] = DateTime(2001,12,29);
namesDataTable->Rows->Add( dRow );
dRow = namesDataTable->NewRow();
dRow->default[ "Name" ] = "Name 4";
dRow->default[ "Date" ] = DateTime(2001,12,13);
namesDataTable->Rows->Add( dRow );
dRow = namesDataTable->NewRow();
dRow->default[ "Name" ] = "Name 5";
dRow->default[ "Date" ] = DateTime(2001,12,21);
namesDataTable->Rows->Add( dRow );
namesDataTable->AcceptChanges();
}
void InitForm()
{
this->Size = System::Drawing::Size( 500, 500 );
grid->Size = System::Drawing::Size( 350, 250 );
grid->TabStop = true;
grid->TabIndex = 1;
this->StartPosition = FormStartPosition::CenterScreen;
this->Controls->Add( grid );
}
};
[STAThread]
int main()
{
Application::Run( gcnew MyForm );
}
using System;
using System.Data;
using System.Windows.Forms;
using System.Drawing;
// This example shows how to create your own column style that
// hosts a control, in this case, a DateTimePicker.
public class DataGridTimePickerColumn : DataGridColumnStyle
{
private CustomDateTimePicker customDateTimePicker1 =
new CustomDateTimePicker();
// The isEditing field tracks whether or not the user is
// editing data with the hosted control.
private bool isEditing;
public DataGridTimePickerColumn() : base()
{
customDateTimePicker1.Visible = false;
}
protected override void Abort(int rowNum)
{
isEditing = false;
customDateTimePicker1.ValueChanged -=
new EventHandler(TimePickerValueChanged);
Invalidate();
}
protected override bool Commit
(CurrencyManager dataSource, int rowNum)
{
customDateTimePicker1.Bounds = Rectangle.Empty;
customDateTimePicker1.ValueChanged -=
new EventHandler(TimePickerValueChanged);
if (!isEditing)
return true;
isEditing = false;
try
{
DateTime value = customDateTimePicker1.Value;
SetColumnValueAtRow(dataSource, rowNum, value);
}
catch (Exception)
{
Abort(rowNum);
return false;
}
Invalidate();
return true;
}
protected override void Edit(
CurrencyManager source,
int rowNum,
Rectangle bounds,
bool readOnly,
string displayText,
bool cellIsVisible)
{
DateTime value = (DateTime)
GetColumnValueAtRow(source, rowNum);
if (cellIsVisible)
{
customDateTimePicker1.Bounds = new Rectangle
(bounds.X + 2, bounds.Y + 2,
bounds.Width - 4, bounds.Height - 4);
customDateTimePicker1.Value = value;
customDateTimePicker1.Visible = true;
customDateTimePicker1.ValueChanged +=
new EventHandler(TimePickerValueChanged);
}
else
{
customDateTimePicker1.Value = value;
customDateTimePicker1.Visible = false;
}
if (customDateTimePicker1.Visible)
DataGridTableStyle.DataGrid.Invalidate(bounds);
customDateTimePicker1.Focus();
}
protected override Size GetPreferredSize(
Graphics g,
object value)
{
return new Size(100, customDateTimePicker1.PreferredHeight + 4);
}
protected override int GetMinimumHeight()
{
return customDateTimePicker1.PreferredHeight + 4;
}
protected override int GetPreferredHeight(Graphics g,
object value)
{
return customDateTimePicker1.PreferredHeight + 4;
}
protected override void Paint(Graphics g,
Rectangle bounds,
CurrencyManager source,
int rowNum)
{
Paint(g, bounds, source, rowNum, false);
}
protected override void Paint(
Graphics g,
Rectangle bounds,
CurrencyManager source,
int rowNum,
bool alignToRight)
{
Paint(
g, bounds,
source,
rowNum,
Brushes.Red,
Brushes.Blue,
alignToRight);
}
protected override void Paint(
Graphics g,
Rectangle bounds,
CurrencyManager source,
int rowNum,
Brush backBrush,
Brush foreBrush,
bool alignToRight)
{
DateTime date = (DateTime)
GetColumnValueAtRow(source, rowNum);
Rectangle rect = bounds;
g.FillRectangle(backBrush, rect);
rect.Offset(0, 2);
rect.Height -= 2;
g.DrawString(date.ToString("d"),
this.DataGridTableStyle.DataGrid.Font,
foreBrush, rect);
}
protected override void SetDataGridInColumn(DataGrid value)
{
base.SetDataGridInColumn(value);
if (customDateTimePicker1.Parent != null)
{
customDateTimePicker1.Parent.Controls.Remove
(customDateTimePicker1);
}
if (value != null)
{
value.Controls.Add(customDateTimePicker1);
}
}
private void TimePickerValueChanged(object sender, EventArgs e)
{
// Remove the handler to prevent it from being called twice in a row.
customDateTimePicker1.ValueChanged -=
new EventHandler(TimePickerValueChanged);
this.isEditing = true;
base.ColumnStartedEditing(customDateTimePicker1);
}
}
public class CustomDateTimePicker : DateTimePicker
{
protected override bool ProcessKeyMessage(ref Message m)
{
// Keep all the keys for the DateTimePicker.
return ProcessKeyEventArgs(ref m);
}
}
public class MyForm : Form
{
private DataTable namesDataTable;
private DataGrid grid = new DataGrid();
public MyForm() : base()
{
InitForm();
namesDataTable = new DataTable("NamesTable");
namesDataTable.Columns.Add(new DataColumn("Name"));
DataColumn dateColumn = new DataColumn
("Date", typeof(DateTime));
dateColumn.DefaultValue = DateTime.Today;
namesDataTable.Columns.Add(dateColumn);
DataSet namesDataSet = new DataSet();
namesDataSet.Tables.Add(namesDataTable);
grid.DataSource = namesDataSet;
grid.DataMember = "NamesTable";
AddGridStyle();
AddData();
}
private void AddGridStyle()
{
DataGridTableStyle myGridStyle = new DataGridTableStyle();
myGridStyle.MappingName = "NamesTable";
DataGridTextBoxColumn nameColumnStyle =
new DataGridTextBoxColumn();
nameColumnStyle.MappingName = "Name";
nameColumnStyle.HeaderText = "Name";
myGridStyle.GridColumnStyles.Add(nameColumnStyle);
DataGridTimePickerColumn timePickerColumnStyle =
new DataGridTimePickerColumn();
timePickerColumnStyle.MappingName = "Date";
timePickerColumnStyle.HeaderText = "Date";
timePickerColumnStyle.Width = 100;
myGridStyle.GridColumnStyles.Add(timePickerColumnStyle);
grid.TableStyles.Add(myGridStyle);
}
private void AddData()
{
DataRow dRow = namesDataTable.NewRow();
dRow["Name"] = "Name 1";
dRow["Date"] = new DateTime(2001, 12, 01);
namesDataTable.Rows.Add(dRow);
dRow = namesDataTable.NewRow();
dRow["Name"] = "Name 2";
dRow["Date"] = new DateTime(2001, 12, 04);
namesDataTable.Rows.Add(dRow);
dRow = namesDataTable.NewRow();
dRow["Name"] = "Name 3";
dRow["Date"] = new DateTime(2001, 12, 29);
namesDataTable.Rows.Add(dRow);
dRow = namesDataTable.NewRow();
dRow["Name"] = "Name 4";
dRow["Date"] = new DateTime(2001, 12, 13);
namesDataTable.Rows.Add(dRow);
dRow = namesDataTable.NewRow();
dRow["Name"] = "Name 5";
dRow["Date"] = new DateTime(2001, 12, 21);
namesDataTable.Rows.Add(dRow);
namesDataTable.AcceptChanges();
}
private void InitForm()
{
this.Size = new Size(500, 500);
grid.Size = new Size(350, 250);
grid.TabStop = true;
grid.TabIndex = 1;
this.StartPosition = FormStartPosition.CenterScreen;
this.Controls.Add(grid);
}
[STAThread]
public static void Main()
{
Application.Run(new MyForm());
}
}
Imports System.Data
Imports System.Windows.Forms
Imports System.Drawing
Imports System.ComponentModel
Imports System.Security.Permissions
' This example shows how to create your own column style that
' hosts a control, in this case, a DateTimePicker.
Public Class DataGridTimePickerColumn
Inherits DataGridColumnStyle
Private customDateTimePicker1 As New CustomDateTimePicker()
' The isEditing field tracks whether or not the user is
' editing data with the hosted control.
Private isEditing As Boolean
Public Sub New()
customDateTimePicker1.Visible = False
End Sub
Protected Overrides Sub Abort(ByVal rowNum As Integer)
isEditing = False
RemoveHandler customDateTimePicker1.ValueChanged, _
AddressOf TimePickerValueChanged
Invalidate()
End Sub
Protected Overrides Function Commit _
(ByVal dataSource As CurrencyManager, ByVal rowNum As Integer) _
As Boolean
customDateTimePicker1.Bounds = Rectangle.Empty
RemoveHandler customDateTimePicker1.ValueChanged, _
AddressOf TimePickerValueChanged
If Not isEditing Then
Return True
End If
isEditing = False
Try
Dim value As DateTime = customDateTimePicker1.Value
SetColumnValueAtRow(dataSource, rowNum, value)
Catch
End Try
Invalidate()
Return True
End Function
Protected Overloads Overrides Sub Edit( _
ByVal [source] As CurrencyManager, _
ByVal rowNum As Integer, _
ByVal bounds As Rectangle, _
ByVal [readOnly] As Boolean, _
ByVal displayText As String, _
ByVal cellIsVisible As Boolean)
Dim value As DateTime = _
CType(GetColumnValueAtRow([source], rowNum), DateTime)
If cellIsVisible Then
customDateTimePicker1.Bounds = New Rectangle _
(bounds.X + 2, bounds.Y + 2, bounds.Width - 4, _
bounds.Height - 4)
customDateTimePicker1.Value = value
customDateTimePicker1.Visible = True
AddHandler customDateTimePicker1.ValueChanged, _
AddressOf TimePickerValueChanged
Else
customDateTimePicker1.Value = value
customDateTimePicker1.Visible = False
End If
If customDateTimePicker1.Visible Then
DataGridTableStyle.DataGrid.Invalidate(bounds)
End If
customDateTimePicker1.Focus()
End Sub
Protected Overrides Function GetPreferredSize( _
ByVal g As Graphics, _
ByVal value As Object) As Size
Return New Size(100, customDateTimePicker1.PreferredHeight + 4)
End Function
Protected Overrides Function GetMinimumHeight() As Integer
Return customDateTimePicker1.PreferredHeight + 4
End Function
Protected Overrides Function GetPreferredHeight( _
ByVal g As Graphics, ByVal value As Object) As Integer
Return customDateTimePicker1.PreferredHeight + 4
End Function
Protected Overloads Overrides Sub Paint( _
ByVal g As Graphics, ByVal bounds As Rectangle, _
ByVal [source] As CurrencyManager, ByVal rowNum As Integer)
Paint(g, bounds, [source], rowNum, False)
End Sub
Protected Overloads Overrides Sub Paint(ByVal g As Graphics, _
ByVal bounds As Rectangle, ByVal [source] As CurrencyManager, _
ByVal rowNum As Integer, ByVal alignToRight As Boolean)
Paint(g, bounds, [source], rowNum, Brushes.Red, _
Brushes.Blue, alignToRight)
End Sub
Protected Overloads Overrides Sub Paint(ByVal g As Graphics, _
ByVal bounds As Rectangle, ByVal [source] As CurrencyManager, _
ByVal rowNum As Integer, ByVal backBrush As Brush, _
ByVal foreBrush As Brush, ByVal alignToRight As Boolean)
Dim [date] As DateTime = _
CType(GetColumnValueAtRow([source], rowNum), DateTime)
Dim rect As Rectangle = bounds
g.FillRectangle(backBrush, rect)
rect.Offset(0, 2)
rect.Height -= 2
g.DrawString([date].ToString("d"), _
Me.DataGridTableStyle.DataGrid.Font, foreBrush, _
RectangleF.FromLTRB(rect.X, rect.Y, rect.Right, rect.Bottom))
End Sub
Protected Overrides Sub SetDataGridInColumn(ByVal value As DataGrid)
MyBase.SetDataGridInColumn(value)
If (customDateTimePicker1.Parent IsNot Nothing) Then
customDateTimePicker1.Parent.Controls.Remove(customDateTimePicker1)
End If
If (value IsNot Nothing) Then
value.Controls.Add(customDateTimePicker1)
End If
End Sub
Private Sub TimePickerValueChanged( _
ByVal sender As Object, ByVal e As EventArgs)
' Remove the handler to prevent it from being called twice in a row.
RemoveHandler customDateTimePicker1.ValueChanged, _
AddressOf TimePickerValueChanged
Me.isEditing = True
MyBase.ColumnStartedEditing(customDateTimePicker1)
End Sub
End Class
Public Class CustomDateTimePicker
Inherits DateTimePicker
<SecurityPermissionAttribute( _
SecurityAction.LinkDemand, Flags := SecurityPermissionFlag.UnmanagedCode)> _
Protected Overrides Function ProcessKeyMessage(ByRef m As Message) As Boolean
' Keep all the keys for the DateTimePicker.
Return ProcessKeyEventArgs(m)
End Function
End Class
Public Class MyForm
Inherits Form
Private namesDataTable As DataTable
Private myGrid As DataGrid = New DataGrid()
Public Sub New()
InitForm()
namesDataTable = New DataTable("NamesTable")
namesDataTable.Columns.Add(New DataColumn("Name"))
Dim dateColumn As DataColumn = _
New DataColumn("Date", GetType(DateTime))
dateColumn.DefaultValue = DateTime.Today
namesDataTable.Columns.Add(dateColumn)
Dim namesDataSet As DataSet = New DataSet()
namesDataSet.Tables.Add(namesDataTable)
myGrid.DataSource = namesDataSet
myGrid.DataMember = "NamesTable"
AddGridStyle()
AddData()
End Sub
Private Sub AddGridStyle()
Dim myGridStyle As DataGridTableStyle = _
New DataGridTableStyle()
myGridStyle.MappingName = "NamesTable"
Dim nameColumnStyle As DataGridTextBoxColumn = _
New DataGridTextBoxColumn()
nameColumnStyle.MappingName = "Name"
nameColumnStyle.HeaderText = "Name"
myGridStyle.GridColumnStyles.Add(nameColumnStyle)
Dim customDateTimePicker1ColumnStyle As DataGridTimePickerColumn = _
New DataGridTimePickerColumn()
customDateTimePicker1ColumnStyle.MappingName = "Date"
customDateTimePicker1ColumnStyle.HeaderText = "Date"
customDateTimePicker1ColumnStyle.Width = 100
myGridStyle.GridColumnStyles.Add(customDateTimePicker1ColumnStyle)
myGrid.TableStyles.Add(myGridStyle)
End Sub
Private Sub AddData()
Dim dRow As DataRow = namesDataTable.NewRow()
dRow("Name") = "Name 1"
dRow("Date") = New DateTime(2001, 12, 1)
namesDataTable.Rows.Add(dRow)
dRow = namesDataTable.NewRow()
dRow("Name") = "Name 2"
dRow("Date") = New DateTime(2001, 12, 4)
namesDataTable.Rows.Add(dRow)
dRow = namesDataTable.NewRow()
dRow("Name") = "Name 3"
dRow("Date") = New DateTime(2001, 12, 29)
namesDataTable.Rows.Add(dRow)
dRow = namesDataTable.NewRow()
dRow("Name") = "Name 4"
dRow("Date") = New DateTime(2001, 12, 13)
namesDataTable.Rows.Add(dRow)
dRow = namesDataTable.NewRow()
dRow("Name") = "Name 5"
dRow("Date") = New DateTime(2001, 12, 21)
namesDataTable.Rows.Add(dRow)
namesDataTable.AcceptChanges()
End Sub
Private Sub InitForm()
Me.Size = New Size(500, 500)
myGrid.Size = New Size(350, 250)
myGrid.TabStop = True
myGrid.TabIndex = 1
Me.StartPosition = FormStartPosition.CenterScreen
Me.Controls.Add(myGrid)
End Sub
<STAThread()> _
Public Shared Sub Main()
Application.Run(New MyForm())
End Sub
End Class
Observações
A coleção de objetos DataGridColumnStyle (o GridColumnStylesCollection) é acedida através da propriedade TableStyles do controlo System.Windows.Forms.DataGrid.
O controlo System.Windows.Forms.DataGrid cria automaticamente uma coleção de objetos DataGridColumnStyle para si quando define a propriedade DataSource para uma fonte de dados apropriada. Os objetos criados são, na verdade, instâncias de uma das seguintes classes que herdam de DataGridColumnStyle: DataGridBoolColumn ou DataGridTextBoxColumn classe.
Para formatar a visualização dos dados, defina a Format propriedade da DataGridTextBoxColumn classe para um dos valores de formatação. Para mais informações sobre valores de formatação válidos, consulte Tipos de Formatação e Cadeias de Formatação Personalizadas de Data e Hora.
Também pode criar o seu próprio conjunto de DataGridColumnStyle objetos e adicioná-los ao GridColumnStylesCollection. Ao fazê-lo, deve definir o MappingName estilo de cada coluna para ColumnName o de a DataColumn para sincronizar a apresentação das colunas com os dados reais.
Caution
Crie DataGridColumnStyle sempre objetos e adicione-os ao GridColumnStylesCollection antes de adicionar DataGridTableStyle objetos ao GridTableStylesCollection. Quando adiciona um vazio DataGridTableStyle com valor válido MappingName à coleção, DataGridColumnStyle os objetos são automaticamente gerados para si. Consequentemente, uma exceção será lançada se tentar adicionar novos DataGridColumnStyle objetos com valores duplicados MappingName ao GridColumnStylesCollection.
Quando uma das classes derivadas é instanciada por um controlo System.Windows.Forms.DataGrid, a classe criada depende do DataType do objeto DataColumn associado ao objeto DataGridColumnStyle. Por exemplo, um DataColumn com o seu DataType conjunto em System.Boolean será associado a um DataGridBoolColumn. Para determinar o tipo de qualquer DataGridColumnStyle, use o GetType método.
Para criar as suas próprias classes de coluna, pode herdar de DataGridColumnStyle. Pode querer fazer isto para criar colunas especiais que hospedam controlos, como exemplificado pela DataGridTextBox classe que hospeda o TextBox controlo. Por exemplo, pode hospedar um Image controlo para mostrar imagens nas colunas, ou pode criar o seu próprio controlo de utilizador para hospedar na coluna.
A funcionalidade do DataGridColumnStyle não deve ser confundida com a do DataColumn. Enquanto o DataColumn contém as propriedades e métodos apropriados para criar o esquema de uma tabela de dados, o DataGridColumnStyle contém as propriedades e métodos relacionados com o aparecimento de uma coluna individual no ecrã.
Se uma linha contiver um DBNull.Value, o texto apresentado na coluna pode ser definido com a NullText propriedade.
A DataGridColumnStyle classe também permite especificar o comportamento de uma coluna enquanto os seus dados estão a ser alterados. Os BeginUpdate métodos e EndUpdate suspendem temporariamente o desenho da coluna enquanto grandes atualizações são feitas aos dados da coluna. Sem esta funcionalidade, cada alteração em cada célula da grelha seria imediatamente desenhada; Isto pode ser distrativo para o utilizador e um risco de desempenho.
Vários métodos permitem monitorizar a coluna à medida que é editada pelo utilizador, incluindo os Edit eventos and (e Commit eventos).
A maioria das propriedades e métodos da classe é adaptada para controlar a aparência de uma coluna. Mas algumas, como o GetColumnValueAtRow e SetColumnValueAtRow permitem-lhe examinar e alterar o valor numa célula específica.
Notas para Implementadores
Quando herdas de DataGridColumnStyle, deves sobrepor os seguintes elementos: Abort(Int32), Commit(CurrencyManager, Int32), Edit(CurrencyManager, Int32, Rectangle, Boolean), e Paint(Graphics, Rectangle, CurrencyManager, Int32) (duas vezes).
Construtores
| Name | Description |
|---|---|
| DataGridColumnStyle() |
Numa classe derivada, inicializa uma nova instância da DataGridColumnStyle classe. |
| DataGridColumnStyle(PropertyDescriptor) |
Inicializa uma nova instância da DataGridColumnStyle classe com o especificado PropertyDescriptor. |
Propriedades
| Name | Description |
|---|---|
| Alignment |
Obtém ou define o alinhamento do texto numa coluna. |
| CanRaiseEvents |
Obtém um valor que indica se o componente pode gerar um evento. (Herdado de Component) |
| Container |
Obtém o IContainer que contém o Component. (Herdado de Component) |
| DataGridTableStyle |
Recebe o DataGridTableStyle para a coluna. |
| DesignMode |
Obtém um valor que indica se o Component está atualmente em modo de design. (Herdado de Component) |
| Events |
Obtém a lista de gestores de eventos que estão ligados a isto Component. (Herdado de Component) |
| FontHeight |
Obtém a altura da fonte da coluna. |
| HeaderAccessibleObject |
Recebe o AccessibleObject para a coluna. |
| HeaderText |
Obtém ou define o texto do cabeçalho da coluna. |
| MappingName |
Obtém ou define o nome do elemento de dados para mapear o estilo da coluna. |
| NullText |
Obtém ou define o texto que é apresentado quando a coluna contém |
| PropertyDescriptor |
Obtém ou define o PropertyDescriptor que determina os atributos dos dados exibidos pelo DataGridColumnStyle. |
| ReadOnly |
Recebe ou define um valor que indica se os dados na coluna podem ser editados. |
| Site |
Obtém ou define o ISite do Component. (Herdado de Component) |
| Width |
Obtém ou define a largura da coluna. |
Métodos
| Name | Description |
|---|---|
| Abort(Int32) |
Quando é sobreposto numa classe derivada, inicia um pedido para interromper um procedimento de edição. |
| BeginUpdate() |
Suspende a pintura da coluna até que o EndUpdate() método seja chamado. |
| CheckValidDataSource(CurrencyManager) |
Lança uma exceção se não DataGrid tiver uma fonte de dados válida, ou se esta coluna não estiver mapeada para uma propriedade válida na fonte de dados. |
| ColumnStartedEditing(Control) |
Informa DataGrid que o utilizador começou a editar a coluna. |
| Commit(CurrencyManager, Int32) |
Quando é sobreposto numa classe derivada, inicia um pedido para completar um procedimento de edição. |
| ConcedeFocus() |
Notifica uma coluna que deve ceder o foco ao controlo que está a hospedar. |
| CreateHeaderAccessibleObject() |
Recebe o AccessibleObject para a coluna. |
| CreateObjRef(Type) |
Cria um objeto que contém toda a informação relevante necessária para gerar um proxy usado para comunicar com um objeto remoto. (Herdado de MarshalByRefObject) |
| Dispose() |
Liberta todos os recursos utilizados pelo Component. (Herdado de Component) |
| Dispose(Boolean) |
Liberta os recursos não geridos usados pelo Component e opcionalmente liberta os recursos geridos. (Herdado de Component) |
| Edit(CurrencyManager, Int32, Rectangle, Boolean, String, Boolean) |
Quando sobrescrito numa classe derivadora, prepara uma célula para edição. |
| Edit(CurrencyManager, Int32, Rectangle, Boolean, String) |
Prepara a célula para edição usando o número de linha e Rectangle parâmetros especificadosCurrencyManager. |
| Edit(CurrencyManager, Int32, Rectangle, Boolean) |
Prepara uma célula para edição. |
| EndUpdate() |
Retoma a pintura de colunas suspensas ao chamar o BeginUpdate() método. |
| EnterNullValue() |
Entra a Value na coluna. |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetColumnValueAtRow(CurrencyManager, Int32) |
Obtém o valor na linha especificada a partir do especificado CurrencyManager. |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetLifetimeService() |
Recupera o objeto de serviço de tempo de vida atual que controla a política de vida útil neste caso. (Herdado de MarshalByRefObject) |
| GetMinimumHeight() |
Quando sobrescrito numa classe derivada, obtém a altura mínima de uma linha. |
| GetPreferredHeight(Graphics, Object) |
Quando sobrescrito numa classe derivada, obtém a altura usada para redimensionar automaticamente as colunas. |
| GetPreferredSize(Graphics, Object) |
Quando sobrescrito numa classe derivada, obtém a largura e a altura do valor especificado. A largura e a altura são usadas quando o utilizador navega para DataGridTableStyle usar o DataGridColumnStyle. |
| GetService(Type) |
Devolve um objeto que representa um serviço fornecido pelo Component ou pelo seu Container. (Herdado de Component) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| InitializeLifetimeService() |
Obtém-se um objeto de serviço vitalício para controlar a apólice vitalícia neste caso. (Herdado de MarshalByRefObject) |
| Invalidate() |
Redesenha a coluna e faz com que seja enviada uma mensagem de pintura para o controlo. |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| MemberwiseClone(Boolean) |
Cria uma cópia superficial do objeto atual MarshalByRefObject . (Herdado de MarshalByRefObject) |
| Paint(Graphics, Rectangle, CurrencyManager, Int32, Boolean) |
Quando sobrescrito numa classe derivada, pinta a DataGridColumnStyle com o número de linha especificado Graphics, Rectangle, CurrencyManager, número de linha e alinhamento. |
| Paint(Graphics, Rectangle, CurrencyManager, Int32, Brush, Brush, Boolean) |
Pinta a DataGridColumnStyle com o especificado Graphics, Rectangle, CurrencyManager, número de linha, cor de fundo, cor do primeiro plano e alinhamento. |
| Paint(Graphics, Rectangle, CurrencyManager, Int32) |
Pinta o DataGridColumnStyle com o número especificado Graphics, Rectangle, CurrencyManager, e o número de linha. |
| ReleaseHostedControl() |
Permite à coluna libertar recursos quando o controlo que aloja não é necessário. |
| ResetHeaderText() |
Reinicia o HeaderText para o seu valor padrão, |
| SetColumnValueAtRow(CurrencyManager, Int32, Object) |
Define o valor numa linha especificada com o valor de um determinado CurrencyManager. |
| SetDataGrid(DataGrid) |
Define o DataGrid controlo a que esta coluna pertence. |
| SetDataGridInColumn(DataGrid) |
Define para DataGrid a coluna. |
| ToString() |
Devolve a String contendo o nome do Component, se existir. Este método não deve ser ultrapassado. (Herdado de Component) |
| UpdateUI(CurrencyManager, Int32, String) |
Atualiza o valor de uma linha especificada com o texto indicado. |
evento
| Name | Description |
|---|---|
| AlignmentChanged |
Ocorre quando o valor da Alignment propriedade muda. |
| Disposed |
Ocorre quando o componente é eliminado por uma chamada ao Dispose() método. (Herdado de Component) |
| FontChanged |
Ocorre quando a fonte da coluna muda. |
| HeaderTextChanged |
Ocorre quando o valor da HeaderText propriedade muda. |
| MappingNameChanged |
Ocorre quando o MappingName valor muda. |
| NullTextChanged |
Ocorre quando o NullText valor muda. |
| PropertyDescriptorChanged |
Ocorre quando o valor da PropertyDescriptor propriedade muda. |
| ReadOnlyChanged |
Ocorre quando o valor da ReadOnly propriedade muda. |
| WidthChanged |
Ocorre quando o valor da Width propriedade muda. |
Implementações de Interface Explícita
| Name | Description |
|---|---|
| IDataGridColumnStyleEditingNotificationService.ColumnStartedEditing(Control) |
Informa o DataGrid controlo que o utilizador começou a editar a coluna. |