DataGridColumnStyle 类

定义

指定 DataGrid 控件列的外观、文本格式和行为。 此类为抽象类。

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
继承
DataGridColumnStyle
派生
实现

示例

下面的代码示例创建承载 DataGridColumnStyle 控件的 DateTimePicker

#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

注解

通过 控件的 DataGridColumnStyle 属性访问System.Windows.Forms.DataGrid () 的 TableStyles 对象的GridColumnStylesCollection集合。

System.Windows.Forms.DataGrid 属性设置为适当的数据源时, DataSource 控件会自动为你创建对象的集合DataGridColumnStyle。 创建的对象实际上是继承自 DataGridColumnStyleDataGridBoolColumnDataGridTextBoxColumn 类的下列类之一的实例。

若要设置数据显示的格式,请将 类的 DataGridTextBoxColumn 属性设置为Format格式设置值之一。 有关有效格式设置值的详细信息,请参阅设置类型和自定义日期和时间格式字符串

还可以创建自己的对象集 DataGridColumnStyle ,并将其添加到 GridColumnStylesCollection。 执行此操作时,必须将每个列样式ColumnName的 设置为 MappingNameDataColumn ,以便将列的显示与实际数据同步。

注意

在将 对象添加到 之前,始终创建 DataGridColumnStyle 对象并将其添加到 DataGridTableStyleGridTableStylesCollectionGridColumnStylesCollection 将具有有效MappingName值的空DataGridTableStyle添加到集合时,DataGridColumnStyle将自动生成对象。 因此,如果尝试将具有重复MappingName值的新DataGridColumnStyle对象添加到 ,GridColumnStylesCollection将引发异常。

当其中一个派生类由System.Windows.Forms.DataGrid控件实例化时,创建的类依赖于DataTypeDataGridColumnStyle 对象关联的 的 DataColumn 。 例如, DataColumn 设置为 DataTypeSystem.Boolean 的 将与 相关联 DataGridBoolColumn。 若要确定任何 DataGridColumnStyle的类型,请使用 GetType 方法。

若要创建自己的列类,可以从 继承 DataGridColumnStyle。 你可能希望这样做,以便创建承载控件的特殊列,如承载控件的 TextBox 类所示DataGridTextBox。 例如,可以托管控件 Image 以在列中显示图片,也可以创建自己的用户控件以托管在列中。

DataGridColumnStyle的功能不应与 DataColumn的功能混淆。 DataColumn而 包含适合创建数据表架构的属性和方法,DataGridColumnStyle而 包含与屏幕上单个列的外观相关的属性和方法。

如果行包含 DBNull.Value,则可以使用 NullText 属性设置列中显示的文本。

DataGridColumnStyle 还允许你在更改列数据时指定列的行为。 BeginUpdateEndUpdate 方法在对列的数据进行大型更新时暂时挂起列的绘制。 如果没有此功能,网格的每个单元格中的每个更改都会立即绘制;这可能会分散用户的注意力,并导致性能责任。

多种方法允许在用户编辑列时监视列,包括 EditCommit 事件。

类的大多数属性和方法都是为控制列的外观而定制的。 但是,一些值(如 GetColumnValueAtRowSetColumnValueAtRow )可用于检查和更改指定单元格中的值。

实施者说明

DataGridColumnStyle继承时,必须重写以下成员: Abort(Int32)Commit(CurrencyManager, Int32)Edit(CurrencyManager, Int32, Rectangle, Boolean)Paint(Graphics, Rectangle, CurrencyManager, Int32) (两次) 。

构造函数

DataGridColumnStyle()

在派生类中,初始化 DataGridColumnStyle 类的新实例。

DataGridColumnStyle(PropertyDescriptor)

使用指定的 DataGridColumnStyle 初始化 PropertyDescriptor 类的新实例。

属性

Alignment

获取或设置列中文本的对齐方式。

CanRaiseEvents

获取一个指示组件是否可以引发事件的值。

(继承自 Component)
Container

获取包含 IContainerComponent

(继承自 Component)
DataGridTableStyle

获取列的 DataGridTableStyle

DesignMode

获取一个值,用以指示 Component 当前是否处于设计模式。

(继承自 Component)
Events

获取附加到此 Component 的事件处理程序的列表。

(继承自 Component)
FontHeight

获取该列字体的高度。

HeaderAccessibleObject

获取列的 AccessibleObject

HeaderText

获取或设置列标题的文本。

MappingName

获取或设置列样式所映射到的数据成员的名称。

NullText

获取或设置在列包含 null 时所显示的文本。

PropertyDescriptor

获取或设置 PropertyDescriptor,它确定 DataGridColumnStyle 所显示数据的特性。

ReadOnly

获取或设置一个值,该值指示该列中的数据是否可以编辑。

Site

获取或设置 ComponentISite

(继承自 Component)
Width

获取或设置列的宽度。

方法

Abort(Int32)

在派生类中被重写时,将启动一个请求来中断编辑过程。

BeginUpdate()

一直挂起列的绘制,直到调用 EndUpdate() 方法为止。

CheckValidDataSource(CurrencyManager)

如果 DataGrid 没有有效数据源,或该列未映射到数据源中的有效属性,将引发异常。

ColumnStartedEditing(Control)

通知 DataGrid 用户已开始编辑该列。

Commit(CurrencyManager, Int32)

在派生类中被重写时,将启动一个请求来完成编辑过程。

ConcedeFocus()

通知列必须放弃它承载的控件的焦点。

CreateHeaderAccessibleObject()

获取列的 AccessibleObject

CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。

(继承自 MarshalByRefObject)
Dispose()

释放由 Component 使用的所有资源。

(继承自 Component)
Dispose(Boolean)

释放由 Component 占用的非托管资源,还可以另外再释放托管资源。

(继承自 Component)
Edit(CurrencyManager, Int32, Rectangle, Boolean)

准备单元格以便进行编辑。

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

使用指定的 CurrencyManager、行号和 Rectangle 参数准备单元格以便进行编辑。

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

当在派生类中被重写时,将准备一个将要进行编辑的单元格。

EndUpdate()

继续绘制由调用 BeginUpdate() 方法而挂起的列。

EnterNullValue()

向列中输入 Value

Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
GetColumnValueAtRow(CurrencyManager, Int32)

获取指定 CurrencyManager 中指定行内的值。

GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetLifetimeService()
已过时.

检索控制此实例的生存期策略的当前生存期服务对象。

(继承自 MarshalByRefObject)
GetMinimumHeight()

在派生类中被重写时,将获取一行的最小高度。

GetPreferredHeight(Graphics, Object)

在派生类中被重写时,将获取自动调整列的大小所用的高度。

GetPreferredSize(Graphics, Object)

在派生类中被重写时,将获取指定值的宽度和高度。 在用户定位到使用 DataGridTableStyleDataGridColumnStyle 时将使用该宽度和高度。

GetService(Type)

返回一个对象,该对象表示由 Component 或它的 Container 提供的服务。

(继承自 Component)
GetType()

获取当前实例的 Type

(继承自 Object)
InitializeLifetimeService()
已过时.

获取生存期服务对象来控制此实例的生存期策略。

(继承自 MarshalByRefObject)
Invalidate()

重新绘制列,并会向控件发送一条绘制消息。

MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。

(继承自 MarshalByRefObject)
Paint(Graphics, Rectangle, CurrencyManager, Int32)

使用指定的 DataGridColumnStyleGraphicsRectangle 和行号绘制 CurrencyManager

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

在派生类中被重写时,将绘制具有指定 DataGridColumnStyleGraphicsRectangle、行号和对齐方式的 CurrencyManager

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

绘制具有指定 DataGridColumnStyleGraphicsRectangle、行号、背景色、前景色和对齐方式的 CurrencyManager

ReleaseHostedControl()

不再需要列所承载的控件时,允许列释放资源。

ResetHeaderText()

HeaderText 重置为其默认值 null

SetColumnValueAtRow(CurrencyManager, Int32, Object)

用来自指定 CurrencyManager 的值设置指定行中的值。

SetDataGrid(DataGrid)

设置该列所属的 DataGrid 控件。

SetDataGridInColumn(DataGrid)

设置列的 DataGrid

ToString()

返回包含 Component 的名称的 String(如果有)。 不应重写此方法。

(继承自 Component)
UpdateUI(CurrencyManager, Int32, String)

用给定的文本更新指定行的值。

事件

AlignmentChanged

Alignment 属性值更改时发生。

Disposed

在通过调用 Dispose() 方法释放组件时发生。

(继承自 Component)
FontChanged

当列的字体更改时发生。

HeaderTextChanged

HeaderText 属性值更改时发生。

MappingNameChanged

MappingName 值更改时发生。

NullTextChanged

NullText 值更改时发生。

PropertyDescriptorChanged

PropertyDescriptor 属性值更改时发生。

ReadOnlyChanged

ReadOnly 属性值更改时发生。

WidthChanged

Width 属性值更改时发生。

显式接口实现

IDataGridColumnStyleEditingNotificationService.ColumnStartedEditing(Control)

通知 DataGrid 控件用户已开始编辑该列。

适用于

另请参阅