DataGridColumnStyle Classe

Definição

Especifica a aparência, a formatação de texto e o comportamento de uma coluna do controle DataGrid.Specifies the appearance, text formatting, and behavior of a DataGrid control column. Esta classe é abstrata.This class is abstract.

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
DataGridColumnStyle
Derivado
Implementações

Exemplos

O exemplo de código a seguir DataGridColumnStyle cria um que DateTimePicker hospeda um controle.The following code example creates a DataGridColumnStyle that hosts a DateTimePicker control.

#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;
using 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 : 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
{
    [SecurityPermissionAttribute(
    SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
    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

Comentários

A coleção de DataGridColumnStyle objetos (o GridColumnStylesCollection) é acessada System.Windows.Forms.DataGrid por meio TableStyles da Propriedade do controle.The collection of DataGridColumnStyle objects (the GridColumnStylesCollection) is accessed through the System.Windows.Forms.DataGrid control's TableStyles property.

O System.Windows.Forms.DataGrid controle cria automaticamente uma coleção de DataGridColumnStyle objetos para você quando você define a DataSource Propriedade como uma fonte de dados apropriada.The System.Windows.Forms.DataGrid control automatically creates a collection of DataGridColumnStyle objects for you when you set the DataSource property to an appropriate data source. Os objetos criados na verdade são instâncias de uma das seguintes classes que herdam DataGridColumnStylede DataGridBoolColumn : DataGridTextBoxColumn ou classe.The objects created actually are instances of one of the following classes that inherit from DataGridColumnStyle: DataGridBoolColumn or DataGridTextBoxColumn class.

Para formatar a exibição de dados, defina Format a propriedade DataGridTextBoxColumn da classe como um dos valores de formatação.To format the data display, set the Format property of the DataGridTextBoxColumn class to one of the formatting values. Para obter mais informações sobre valores de formatação válidos, consulte tipos de formatação e cadeias de caracteres de formato de data e hora personalizadas.For more information about valid formatting values, see Formatting Types and Custom Date and Time Format Strings.

Você também pode criar seu próprio conjunto de DataGridColumnStyle objetos e adicioná-lo GridColumnStylesCollectionao.You can also create your own set of DataGridColumnStyle objects and add them to the GridColumnStylesCollection. Ao fazer isso, você deve definir o MappingName de cada estilo de coluna como o ColumnName de DataColumn a para sincronizar a exibição de colunas com os dados reais.When you do so, you must set the MappingName of each column style to the ColumnName of a DataColumn to synchronize the display of columns with the actual data.

Cuidado

Sempre crie DataGridColumnStyle objetos e adicione-os GridColumnStylesCollection ao GridTableStylesCollectionantes de DataGridTableStyle adicionar objetos ao.Always create DataGridColumnStyle objects and add them to the GridColumnStylesCollection before adding DataGridTableStyle objects to the GridTableStylesCollection. Quando você adiciona um vazio DataGridTableStyle com um valor MappingName válido à coleção, DataGridColumnStyle os objetos são gerados automaticamente para você.When you add an empty DataGridTableStyle with a valid MappingName value to the collection, DataGridColumnStyle objects are automatically generated for you. Consequentemente, uma exceção será gerada se você tentar adicionar novos DataGridColumnStyle objetos com valores duplicados MappingName ao GridColumnStylesCollection.Consequently, an exception will be thrown if you try to add new DataGridColumnStyle objects with duplicate MappingName values to the GridColumnStylesCollection.

Quando uma das classes derivadas é System.Windows.Forms.DataGrid instanciada por um controle, a classe criada depende DataType do DataGridColumnStyle do DataColumn associado ao objeto.When one of the derived classes is instantiated by a System.Windows.Forms.DataGrid control, the class created depends on the DataType of the DataColumn associated with the DataGridColumnStyle object. Por exemplo, um DataColumn com seu DataType definido como System.Boolean será associado a um DataGridBoolColumn.For example, a DataColumn with its DataType set to System.Boolean will be associated with a DataGridBoolColumn. Para determinar o tipo de qualquer DataGridColumnStyleum, use GetType o método.To determine the type of any DataGridColumnStyle, use the GetType method.

Para criar suas próprias classes de coluna, você pode herdar de DataGridColumnStyle.To create your own column classes, you can inherit from DataGridColumnStyle. Talvez você queira fazer isso para criar colunas especiais que hospedam controles, como exemplificado pela DataGridTextBox classe, que hospeda o TextBox controle.You might want to do this in order to create special columns that host controls, as exemplified by the DataGridTextBox class, which hosts the TextBox control. Por exemplo, você pode hospedar um Image controle para mostrar imagens em colunas ou pode criar seu próprio controle de usuário para hospedar na coluna.For example, you can host an Image control to show pictures in columns, or you can create your own user control to host in the column.

A funcionalidade do DataGridColumnStyle não deve ser confundida com a DataColumndo.The functionality of the DataGridColumnStyle shouldn't be confused with that of the DataColumn. Enquanto o DataColumn contém as propriedades e os métodos apropriados para criar o esquema de uma tabela de DataGridColumnStyle dados, o contém as propriedades e os métodos relacionados à aparência de uma coluna individual na tela.Whereas the DataColumn contains the properties and methods appropriate to creating a data table's schema, the DataGridColumnStyle contains the properties and methods related to the appearance of an individual column on the screen.

Se uma linha contiver DBNull.Valueum, o texto exibido na coluna poderá ser definido com a NullText propriedade.If a row contains a DBNull.Value, the text displayed in the column can be set with the NullText property.

A DataGridColumnStyle classe também permite que você especifique o comportamento de uma coluna enquanto seus dados estão sendo alterados.The DataGridColumnStyle class also allows you to specify the behavior of a column while its data is being changed. Os BeginUpdate métodos EndUpdate e temporariamente suspendem o desenho da coluna enquanto atualizações grandes são feitas nos dados da coluna.The BeginUpdate and EndUpdate methods temporarily suspend the drawing of the column while large updates are being made to the column's data. Sem essa funcionalidade, todas as alterações em cada célula da grade seriam desenhadas imediatamente; Isso pode estar me distraindo do usuário e de uma responsabilidade de desempenho.Without this functionality, every change in every cell of the grid would be immediately drawn; this could be distracting to the user and a performance liability.

Vários métodos permitem o monitoramento da coluna conforme ela é editada pelo usuário, incluindo os Edit eventos Commit e.Several methods allow monitoring of the column as it is edited by the user, including the Edit and Commit events.

A maioria das propriedades e métodos da classe é adaptada para controlar a aparência de uma coluna.Most of the properties and methods of the class are tailored to controlling a column's appearance. Mas alguns, como o GetColumnValueAtRow e SetColumnValueAtRow permitem que você examine e altere o valor em uma célula especificada.But a few, such as the GetColumnValueAtRow and SetColumnValueAtRow allow you to examine and change the value in a specified cell.

Notas aos Herdeiros

Ao herdar do DataGridColumnStyle, você deve substituir os seguintes membros: Abort(Int32), Commit(CurrencyManager, Int32), Edit(CurrencyManager, Int32, Rectangle, Boolean)e Paint(Graphics, Rectangle, CurrencyManager, Int32) (duas vezes).When you inherit from DataGridColumnStyle, you must override the following members: Abort(Int32), Commit(CurrencyManager, Int32), Edit(CurrencyManager, Int32, Rectangle, Boolean), and Paint(Graphics, Rectangle, CurrencyManager, Int32) (twice).

Construtores

DataGridColumnStyle()

Em uma classe derivada, inicializa uma nova instância da classe DataGridColumnStyle.In a derived class, initializes a new instance of the DataGridColumnStyle class.

DataGridColumnStyle(PropertyDescriptor)

Inicializa uma nova instância da classe DataGridColumnStyle com o PropertyDescriptor especificado.Initializes a new instance of the DataGridColumnStyle class with the specified PropertyDescriptor.

Propriedades

Alignment

Obtém ou define o alinhamento do texto em uma coluna.Gets or sets the alignment of text in a column.

CanRaiseEvents

Obtém um valor que indica se o componente pode acionar um evento.Gets a value indicating whether the component can raise an event.

(Herdado de Component)
Container

Obtém o IContainer que contém o Component.Gets the IContainer that contains the Component.

(Herdado de Component)
DataGridTableStyle

Obtém o DataGridTableStyle da coluna.Gets the DataGridTableStyle for the column.

DesignMode

Obtém um valor que indica se o Component está no modo de design no momento.Gets a value that indicates whether the Component is currently in design mode.

(Herdado de Component)
Events

Obtém a lista de manipuladores de eventos que estão anexados a este Component.Gets the list of event handlers that are attached to this Component.

(Herdado de Component)
FontHeight

Obtém a altura da fonte da coluna.Gets the height of the column's font.

HeaderAccessibleObject

Obtém o AccessibleObject da coluna.Gets the AccessibleObject for the column.

HeaderText

Obtém ou define o contexto do cabeçalho da coluna.Gets or sets the text of the column header.

MappingName

Obtém ou define o nome do membro de dados para o qual mapear o estilo da coluna.Gets or sets the name of the data member to map the column style to.

NullText

Obtém ou define o texto que é exibido quando a coluna contém null.Gets or sets the text that is displayed when the column contains null.

PropertyDescriptor

Obtém ou define o PropertyDescriptor que determina os atributos dos dados exibidos pelo DataGridColumnStyle.Gets or sets the PropertyDescriptor that determines the attributes of data displayed by the DataGridColumnStyle.

ReadOnly

Obtém ou define um valor que indica se os dados na coluna podem ser editados.Gets or sets a value indicating whether the data in the column can be edited.

Site

Obtém ou define o ISite do Component.Gets or sets the ISite of the Component.

(Herdado de Component)
Width

Obtém ou define a largura da coluna.Gets or sets the width of the column.

Métodos

Abort(Int32)

Quando substituído em uma classe derivada, inicia uma solicitação para interromper um procedimento de edição.When overridden in a derived class, initiates a request to interrupt an edit procedure.

BeginUpdate()

Suspende a pintura da coluna até que o método EndUpdate() seja chamado.Suspends the painting of the column until the EndUpdate() method is called.

CheckValidDataSource(CurrencyManager)

Gera uma exceção se o DataGrid não tem uma fonte de dados válido ou se essa coluna não está mapeada para uma propriedade válida na fonte de dados.Throws an exception if the DataGrid does not have a valid data source, or if this column is not mapped to a valid property in the data source.

ColumnStartedEditing(Control)

Informa ao DataGrid que o usuário começou a editar a coluna.Informs the DataGrid that the user has begun editing the column.

Commit(CurrencyManager, Int32)

Quando substituído em uma classe derivada, inicia uma solicitação para concluir um procedimento de edição.When overridden in a derived class, initiates a request to complete an editing procedure.

ConcedeFocus()

Notifica uma coluna de que ela deve liberar o foco para o controle que está hospedando.Notifies a column that it must relinquish the focus to the control it is hosting.

CreateHeaderAccessibleObject()

Obtém o AccessibleObject da coluna.Gets the AccessibleObject for the column.

CreateObjRef(Type)

Cria um objeto que contém todas as informações relevantes necessárias para gerar um proxy usado para se comunicar com um objeto remoto.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Herdado de MarshalByRefObject)
Dispose()

Libera todos os recursos usados pelo Component.Releases all resources used by the Component.

(Herdado de Component)
Dispose(Boolean)

Libera os recursos não gerenciados usados pelo Component e opcionalmente libera os recursos gerenciados.Releases the unmanaged resources used by the Component and optionally releases the managed resources.

(Herdado de Component)
Edit(CurrencyManager, Int32, Rectangle, Boolean)

Prepara uma célula para edição.Prepares a cell for editing.

Edit(CurrencyManager, Int32, Rectangle, Boolean, String)

Prepara a célula para edição usando o CurrencyManager, o número da linha e os parâmetros Rectangle especificados.Prepares the cell for editing using the specified CurrencyManager, row number, and Rectangle parameters.

Edit(CurrencyManager, Int32, Rectangle, Boolean, String, Boolean)

Quando substituído em uma classe derivada, prepara uma célula para edição.When overridden in a deriving class, prepares a cell for editing.

EndUpdate()

Retoma a pintura de colunas suspensa chamando o método BeginUpdate().Resumes the painting of columns suspended by calling the BeginUpdate() method.

EnterNullValue()

Insere um Value na coluna.Enters a Value into the column.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Herdado de Object)
GetColumnValueAtRow(CurrencyManager, Int32)

Obtém o valor na linha especificada do CurrencyManager especificado.Gets the value in the specified row from the specified CurrencyManager.

GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Herdado de Object)
GetLifetimeService()

Recupera o objeto de serviço de tempo de vida atual que controla a política de ciclo de vida para esta instância.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Herdado de MarshalByRefObject)
GetMinimumHeight()

Quando substituído em uma classe derivada, obtém a altura mínima de uma linha.When overridden in a derived class, gets the minimum height of a row.

GetPreferredHeight(Graphics, Object)

Quando substituído em uma classe derivada, obtém a altura usada para redimensionar automaticamente as colunas.When overridden in a derived class, gets the height used for automatically resizing columns.

GetPreferredSize(Graphics, Object)

Quando substituída em uma classe derivada, obtém a largura e a altura do valor especificado.When overridden in a derived class, gets the width and height of the specified value. A largura e altura são usadas quando o usuário navega para DataGridTableStyle usando o DataGridColumnStyle.The width and height are used when the user navigates to DataGridTableStyle using the DataGridColumnStyle.

GetService(Type)

Retorna um objeto que representa um serviço fornecido pelo Component ou pelo seu Container.Returns an object that represents a service provided by the Component or by its Container.

(Herdado de Component)
GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
InitializeLifetimeService()

Obtém um objeto de serviço de tempo de vida para controlar a política de tempo de vida para essa instância.Obtains a lifetime service object to control the lifetime policy for this instance.

(Herdado de MarshalByRefObject)
Invalidate()

Redesenha a coluna e faz com que uma mensagem de pintura seja enviada para o controle.Redraws the column and causes a paint message to be sent to the control.

MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
MemberwiseClone(Boolean)

Cria uma cópia superficial do objeto MarshalByRefObject atual.Creates a shallow copy of the current MarshalByRefObject object.

(Herdado de MarshalByRefObject)
Paint(Graphics, Rectangle, CurrencyManager, Int32)

Pinta o DataGridColumnStyle com o Graphics, Rectangle, CurrencyManager e o número de linha especificados.Paints the DataGridColumnStyle with the specified Graphics, Rectangle, CurrencyManager, and row number.

Paint(Graphics, Rectangle, CurrencyManager, Int32, Boolean)

Quando substituído em uma classe derivada, pinta uma DataGridColumnStyle com o Graphics, Rectangle, CurrencyManager, número de linha e alinhamento especificados.When overridden in a derived class, paints a DataGridColumnStyle with the specified Graphics, Rectangle, CurrencyManager, row number, and alignment.

Paint(Graphics, Rectangle, CurrencyManager, Int32, Brush, Brush, Boolean)

Pinta uma DataGridColumnStyle com o Graphics, Rectangle, CurrencyManager, número da linha, cor da tela de fundo, cor de primeiro plano e alinhamento especificados.Paints a DataGridColumnStyle with the specified Graphics, Rectangle, CurrencyManager, row number, background color, foreground color, and alignment.

ReleaseHostedControl()

Permite que a coluna libere recursos quando o controle que ela hospeda não é necessário.Allows the column to free resources when the control it hosts is not needed.

ResetHeaderText()

Redefine o HeaderText para seu valor padrão, null.Resets the HeaderText to its default value, null.

SetColumnValueAtRow(CurrencyManager, Int32, Object)

Define o valor em uma linha especificada com o valor de um CurrencyManager especificado.Sets the value in a specified row with the value from a specified CurrencyManager.

SetDataGrid(DataGrid)

Define o controle DataGrid ao qual esta coluna pertence.Sets the DataGrid control that this column belongs to.

SetDataGridInColumn(DataGrid)

Define o DataGrid para a coluna.Sets the DataGrid for the column.

ToString()

Retorna um String que contém o nome do Component, se houver.Returns a String containing the name of the Component, if any. Esse método não deve ser substituído.This method should not be overridden.

(Herdado de Component)
UpdateUI(CurrencyManager, Int32, String)

Atualiza o valor de uma linha especificada com o texto especificado.Updates the value of a specified row with the given text.

Eventos

AlignmentChanged

Ocorre quando o valor da propriedade Alignment muda.Occurs when the Alignment property value changes.

Disposed

Ocorre quando o componente é disposto por uma chamada para o método Dispose().Occurs when the component is disposed by a call to the Dispose() method.

(Herdado de Component)
FontChanged

Ocorre quando a fonte da coluna é alterada.Occurs when the column's font changes.

HeaderTextChanged

Ocorre quando o valor da propriedade HeaderText muda.Occurs when the HeaderText property value changes.

MappingNameChanged

Ocorre quando o valor MappingName é alterado.Occurs when the MappingName value changes.

NullTextChanged

Ocorre quando o valor NullText é alterado.Occurs when the NullText value changes.

PropertyDescriptorChanged

Ocorre quando o valor da propriedade PropertyDescriptor muda.Occurs when the PropertyDescriptor property value changes.

ReadOnlyChanged

Ocorre quando o valor da propriedade ReadOnly muda.Occurs when the ReadOnly property value changes.

WidthChanged

Ocorre quando o valor da propriedade Width muda.Occurs when the Width property value changes.

Implantações explícitas de interface

IDataGridColumnStyleEditingNotificationService.ColumnStartedEditing(Control)

Informa ao controle DataGrid que o usuário começou a editar a coluna.Informs the DataGrid control that the user has begun editing the column.

Aplica-se a

Veja também