DataGridColumnStyle Clase

Definición

Especifica la apariencia, el formato de texto y el comportamiento de una columna de un control DataGrid.Specifies the appearance, text formatting, and behavior of a DataGrid control column. Esta clase es abstracta.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
Herencia
DataGridColumnStyle
Derivado
Implementaciones

Ejemplos

En el ejemplo de código siguiente DataGridColumnStyle se crea un DateTimePicker que hospeda un control.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

Comentarios

Se obtiene acceso DataGridColumnStyle a la colección GridColumnStylesCollectionde objetos () a través System.Windows.Forms.DataGrid de la TableStyles propiedad del control.The collection of DataGridColumnStyle objects (the GridColumnStylesCollection) is accessed through the System.Windows.Forms.DataGrid control's TableStyles property.

El System.Windows.Forms.DataGrid control crea automáticamente una colección de DataGridColumnStyle objetos cuando se establece la DataSource propiedad en un origen de datos adecuado.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. Los objetos creados realmente son instancias de una de las clases siguientes que heredan DataGridColumnStylede DataGridBoolColumn : DataGridTextBoxColumn o clase.The objects created actually are instances of one of the following classes that inherit from DataGridColumnStyle: DataGridBoolColumn or DataGridTextBoxColumn class.

Para dar formato a la presentación de datos Format , establezca la DataGridTextBoxColumn propiedad de la clase en uno de los valores de formato.To format the data display, set the Format property of the DataGridTextBoxColumn class to one of the formatting values. Para obtener más información sobre los valores de formato válidos, vea aplicar formato a tipos y cadenas de formato de fecha y hora personalizado.For more information about valid formatting values, see Formatting Types and Custom Date and Time Format Strings.

También puede crear su propio conjunto de DataGridColumnStyle objetos y agregarlos GridColumnStylesCollectiona.You can also create your own set of DataGridColumnStyle objects and add them to the GridColumnStylesCollection. Al hacerlo, debe establecer el MappingName de cada estilo de columna en el ColumnName de un DataColumn para sincronizar la presentación de columnas con los datos reales.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.

Precaución

Cree DataGridColumnStyle siempre objetos y agréguelos GridColumnStylesCollection DataGridTableStyle aGridTableStylesCollectionantes de agregar objetos a.Always create DataGridColumnStyle objects and add them to the GridColumnStylesCollection before adding DataGridTableStyle objects to the GridTableStylesCollection. Cuando se agrega un vacío DataGridTableStyle con un valor MappingName válido a la colección, DataGridColumnStyle los objetos se generan automáticamente.When you add an empty DataGridTableStyle with a valid MappingName value to the collection, DataGridColumnStyle objects are automatically generated for you. Por consiguiente, se producirá una excepción si intenta agregar nuevos DataGridColumnStyle objetos con valores duplicados MappingName a. GridColumnStylesCollectionConsequently, an exception will be thrown if you try to add new DataGridColumnStyle objects with duplicate MappingName values to the GridColumnStylesCollection.

Cuando un System.Windows.Forms.DataGrid control crea una instancia de una de las clases derivadas, la clase creada depende DataType de la propiedad DataColumn DataGridColumnStyle del asociado al 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 ejemplo, un DataColumn con su DataType establecido en System.Boolean se asociará DataGridBoolColumna.For example, a DataColumn with its DataType set to System.Boolean will be associated with a DataGridBoolColumn. Para determinar el tipo de cualquiera DataGridColumnStyle, use el GetType método.To determine the type of any DataGridColumnStyle, use the GetType method.

Para crear sus propias clases de columna, puede heredar DataGridColumnStylede.To create your own column classes, you can inherit from DataGridColumnStyle. Puede que desee hacer esto para crear columnas especiales que hospeden controles, como ejemplifica la DataGridTextBox clase, que hospeda el TextBox control.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 ejemplo, puede hospedar un Image control para mostrar las imágenes en columnas, o puede crear su propio control de usuario para hospedarlo en la columna.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.

La funcionalidad de DataGridColumnStyle no debe confundirse con la DataColumnde.The functionality of the DataGridColumnStyle shouldn't be confused with that of the DataColumn. Mientras que DataGridColumnStyle contiene las propiedades y los métodos adecuados para crear el esquema de una tabla de datos, contiene las propiedades y los métodos relacionados con la apariencia de una columna individual en la pantalla. DataColumnWhereas 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.

Si una fila contiene DBNull.Value, el texto que se muestra en la columna se puede establecer con la NullText propiedad.If a row contains a DBNull.Value, the text displayed in the column can be set with the NullText property.

La DataGridColumnStyle clase también permite especificar el comportamiento de una columna mientras se cambian sus datos.The DataGridColumnStyle class also allows you to specify the behavior of a column while its data is being changed. Los BeginUpdate métodos EndUpdate y suspenden temporalmente el dibujo de la columna mientras se realizan actualizaciones grandes en los datos de la columna.The BeginUpdate and EndUpdate methods temporarily suspend the drawing of the column while large updates are being made to the column's data. Sin esta funcionalidad, se dibujarán inmediatamente todos los cambios en cada celda de la cuadrícula. Esto puede resultar molesto para el usuario y una responsabilidad de rendimiento.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.

Varios métodos permiten la supervisión de la columna cuando la edita el usuario, incluidos los Edit eventos y. CommitSeveral methods allow monitoring of the column as it is edited by the user, including the Edit and Commit events.

La mayoría de las propiedades y los métodos de la clase se adaptan para controlar la apariencia de una columna.Most of the properties and methods of the class are tailored to controlling a column's appearance. Pero algunos, GetColumnValueAtRow como y SetColumnValueAtRow permiten examinar y cambiar el valor de una celda especificada.But a few, such as the GetColumnValueAtRow and SetColumnValueAtRow allow you to examine and change the value in a specified cell.

Notas a los desarrolladores de herederos

Al heredar de DataGridColumnStyle, debe reemplazar los miembros siguientes: Abort(Int32), Commit(CurrencyManager, Int32), Edit(CurrencyManager, Int32, Rectangle, Boolean)y Paint(Graphics, Rectangle, CurrencyManager, Int32) (dos veces).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).

Constructores

DataGridColumnStyle()

En una clase derivada, inicializa una nueva instancia de la clase DataGridColumnStyle.In a derived class, initializes a new instance of the DataGridColumnStyle class.

DataGridColumnStyle(PropertyDescriptor)

Inicializa una nueva instancia de la clase DataGridColumnStyle con el objeto PropertyDescriptor especificado.Initializes a new instance of the DataGridColumnStyle class with the specified PropertyDescriptor.

Propiedades

Alignment

Obtiene o establece la alineación de texto de una columna.Gets or sets the alignment of text in a column.

CanRaiseEvents

Obtiene un valor que indica si el componente puede generar un evento.Gets a value indicating whether the component can raise an event.

(Heredado de Component)
Container

Obtiene IContainer que contiene Component.Gets the IContainer that contains the Component.

(Heredado de Component)
DataGridTableStyle

Obtiene el DataGridTableStyle de la columna.Gets the DataGridTableStyle for the column.

DesignMode

Obtiene un valor que indica si Component está actualmente en modo de diseño.Gets a value that indicates whether the Component is currently in design mode.

(Heredado de Component)
Events

Obtiene la lista de controladores de eventos asociados a Component.Gets the list of event handlers that are attached to this Component.

(Heredado de Component)
FontHeight

Obtiene el alto de la fuente de la columna.Gets the height of the column's font.

HeaderAccessibleObject

Obtiene el AccessibleObject de la columna.Gets the AccessibleObject for the column.

HeaderText

Obtiene o establece el texto del encabezado de columna.Gets or sets the text of the column header.

MappingName

Obtiene o establece el nombre del miembro de datos para asignar el estilo de columna.Gets or sets the name of the data member to map the column style to.

NullText

Obtiene o establece el texto que se muestra cuando la columna contiene un valor null.Gets or sets the text that is displayed when the column contains null.

PropertyDescriptor

Obtiene o establece el objeto PropertyDescriptor que determina los atributos de los datos que muestra DataGridColumnStyle.Gets or sets the PropertyDescriptor that determines the attributes of data displayed by the DataGridColumnStyle.

ReadOnly

Obtiene o establece un valor que indica si se pueden editar los datos de la columna.Gets or sets a value indicating whether the data in the column can be edited.

Site

Obtiene o establece el ISite de Component.Gets or sets the ISite of the Component.

(Heredado de Component)
Width

Obtiene o establece el ancho de la columna.Gets or sets the width of the column.

Métodos

Abort(Int32)

Cuando se reemplaza en una clase derivada, inicia una solicitud para interrumpir un procedimiento de edición.When overridden in a derived class, initiates a request to interrupt an edit procedure.

BeginUpdate()

Suspende el proceso de pintar la columna hasta que se llama al método EndUpdate().Suspends the painting of the column until the EndUpdate() method is called.

CheckValidDataSource(CurrencyManager)

Produce una excepción si DataGrid no tiene un origen de datos válido o si esta columna no está asignada a una propiedad válida en el origen de datos.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 a DataGrid de que el usuario ha empezado a editar la columna.Informs the DataGrid that the user has begun editing the column.

Commit(CurrencyManager, Int32)

Cuando se reemplaza en una clase derivada, inicia una solicitud para completar un procedimiento de edición.When overridden in a derived class, initiates a request to complete an editing procedure.

ConcedeFocus()

Notifica a una columna que debe ceder el foco al control que hospeda.Notifies a column that it must relinquish the focus to the control it is hosting.

CreateHeaderAccessibleObject()

Obtiene el AccessibleObject de la columna.Gets the AccessibleObject for the column.

CreateObjRef(Type)

Crea un objeto que contiene toda la información relevante necesaria para generar un proxy utilizado para comunicarse con un objeto remoto.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Heredado de MarshalByRefObject)
Dispose()

Libera todos los recursos que usa Component.Releases all resources used by the Component.

(Heredado de Component)
Dispose(Boolean)

Libera los recursos no administrados que usa Component y, de forma opcional, libera los recursos administrados.Releases the unmanaged resources used by the Component and optionally releases the managed resources.

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

Prepara una celda para que pueda editarse.Prepares a cell for editing.

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

Prepara la celda para su edición mediante los parámetros especificados para CurrencyManager, Rectangle y número de fila.Prepares the cell for editing using the specified CurrencyManager, row number, and Rectangle parameters.

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

Cuando se reemplaza en una clase derivada, prepara una celda para su edición.When overridden in a deriving class, prepares a cell for editing.

EndUpdate()

Reanuda la pintura de las columnas que se suspendió mediante la llamada al método BeginUpdate().Resumes the painting of columns suspended by calling the BeginUpdate() method.

EnterNullValue()

Escribe un Value en la columna.Enters a Value into the column.

Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Heredado de Object)
GetColumnValueAtRow(CurrencyManager, Int32)

Obtiene el valor en la fila especificada a partir del objeto CurrencyManager especificado.Gets the value in the specified row from the specified CurrencyManager.

GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Heredado de Object)
GetLifetimeService()

Recupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Heredado de MarshalByRefObject)
GetMinimumHeight()

Cuando se reemplaza en una clase derivada, obtiene el alto mínimo de una fila.When overridden in a derived class, gets the minimum height of a row.

GetPreferredHeight(Graphics, Object)

Cuando se reemplaza en una clase derivada, obtiene el alto que se utiliza para cambiar automáticamente el tamaño de las columnas.When overridden in a derived class, gets the height used for automatically resizing columns.

GetPreferredSize(Graphics, Object)

Cuando se reemplaza en una clase derivada, obtiene el ancho y el alto del valor especificado.When overridden in a derived class, gets the width and height of the specified value. El ancho y el alto se utilizan cuando el usuario navega hasta DataGridTableStyle mediante DataGridColumnStyle.The width and height are used when the user navigates to DataGridTableStyle using the DataGridColumnStyle.

GetService(Type)

Devuelve un objeto que representa el servicio suministrado por Component o por Container.Returns an object that represents a service provided by the Component or by its Container.

(Heredado de Component)
GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Heredado de Object)
InitializeLifetimeService()

Obtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia.Obtains a lifetime service object to control the lifetime policy for this instance.

(Heredado de MarshalByRefObject)
Invalidate()

Vuelve a dibujar la columna y hace que se envíe un mensaje de pintura al control.Redraws the column and causes a paint message to be sent to the control.

MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Heredado de Object)
MemberwiseClone(Boolean)

Crea una copia superficial del objeto MarshalByRefObject actual.Creates a shallow copy of the current MarshalByRefObject object.

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

Pinta DataGridColumnStyle con los valores especificados para Graphics, Rectangle, CurrencyManager y número de fila.Paints the DataGridColumnStyle with the specified Graphics, Rectangle, CurrencyManager, and row number.

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

Cuando se reemplaza en una clase derivada, pinta DataGridColumnStyle con los valores especificados para Graphics, Rectangle, CurrencyManager, número de fila y alineación.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 DataGridColumnStyle con los valores especificados para Graphics, Rectangle, CurrencyManager, número de fila, color de fondo, color de primer plano y alineación.Paints a DataGridColumnStyle with the specified Graphics, Rectangle, CurrencyManager, row number, background color, foreground color, and alignment.

ReleaseHostedControl()

Permite que la columna libere recursos cuando el control contenido en la misma no es necesario.Allows the column to free resources when the control it hosts is not needed.

ResetHeaderText()

Restablece el valor predeterminado null en la propiedad HeaderText.Resets the HeaderText to its default value, null.

SetColumnValueAtRow(CurrencyManager, Int32, Object)

Establece el valor de una fila especificada con el valor de un objeto CurrencyManager especificado.Sets the value in a specified row with the value from a specified CurrencyManager.

SetDataGrid(DataGrid)

Establece el control DataGrid al que pertenece esta columna.Sets the DataGrid control that this column belongs to.

SetDataGridInColumn(DataGrid)

Establece DataGrid para la columna.Sets the DataGrid for the column.

ToString()

Devuelve una String que contiene el nombre del Component, si existe.Returns a String containing the name of the Component, if any. Este método no se debe invalidar.This method should not be overridden.

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

Actualiza el valor de una fila especificada con el texto dado.Updates the value of a specified row with the given text.

Eventos

AlignmentChanged

Se produce cuando cambia el valor de la propiedad Alignment.Occurs when the Alignment property value changes.

Disposed

Se produce cuando el componente se elimina mediante una llamada al método Dispose().Occurs when the component is disposed by a call to the Dispose() method.

(Heredado de Component)
FontChanged

Aparece cuando cambia la fuente de la columna.Occurs when the column's font changes.

HeaderTextChanged

Se produce cuando cambia el valor de la propiedad HeaderText.Occurs when the HeaderText property value changes.

MappingNameChanged

Se produce cuando cambia el valor MappingName.Occurs when the MappingName value changes.

NullTextChanged

Se produce cuando cambia el valor NullText.Occurs when the NullText value changes.

PropertyDescriptorChanged

Se produce cuando cambia el valor de la propiedad PropertyDescriptor.Occurs when the PropertyDescriptor property value changes.

ReadOnlyChanged

Se produce cuando cambia el valor de la propiedad ReadOnly.Occurs when the ReadOnly property value changes.

WidthChanged

Se produce cuando cambia el valor de la propiedad Width.Occurs when the Width property value changes.

Implementaciones de interfaz explícitas

IDataGridColumnStyleEditingNotificationService.ColumnStartedEditing(Control)

Informa al control DataGrid de que el usuario ha comenzado a editar la columna.Informs the DataGrid control that the user has begun editing the column.

Se aplica a

Consulte también: