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

備註

() 物件集合 DataGridColumnStyleGridColumnStylesCollection 是透過 System.Windows.Forms.DataGrid 控制項的 TableStyles 屬性來存取。

當您將 屬性設定 DataSource 為適當的資料來源時,控制項 System.Windows.Forms.DataGrid 會自動為您建立 物件的集合 DataGridColumnStyle 。 建立的物件實際上是繼承自 DataGridColumnStyleDataGridBoolColumnDataGridTextBoxColumn 類別的下列其中一個類別的實例。

若要格式化資料顯示,請將 Format 類別的 DataGridTextBoxColumn 屬性設定為其中一個格式化值。 如需有效格式化值的詳細資訊,請參閱格式化類型和自訂日期和時間格式字串

您也可以建立自己的物件集 DataGridColumnStyle ,並將其新增至 GridColumnStylesCollection 。 當您這樣做時,必須將每個資料行樣式的 設定 MappingNameColumnNameDataColumn ,以同步處理資料行與實際資料的顯示。

警告

一律先建立 DataGridColumnStyle 物件,並在將物件新增至 GridColumnStylesCollection 之前將其新增 DataGridTableStyleGridTableStylesCollection 。 當您將具有有效 MappingName 值的空白 DataGridTableStyle 加入至集合時, DataGridColumnStyle 系統會自動為您產生 物件。 因此,如果您嘗試將具有重複 MappingName 值的新 DataGridColumnStyle 物件新增至 GridColumnStylesCollection ,就會擲回例外狀況。

當控制項具現化其中一個 System.Windows.Forms.DataGrid 衍生類別時,所建立的類別取決於 DataTypeDataColumn 與 物件相關聯的 DataGridColumnStyle 。 例如, DataColumn 其 設定為 System.Boolean 的 會與 相關聯 DataGridBoolColumnDataType 。 若要判斷任何 DataGridColumnStyle 的類型,請使用 GetType 方法。

若要建立自己的資料行類別,您可以從 繼承。 DataGridColumnStyle 您可以執行此動作,以建立裝載控制項的特殊資料行,如裝載控制項的 DataGridTextBoxTextBox 類別所示。 例如,您可以裝載 Image 控制項來顯示資料行中的圖片,也可以建立自己的使用者控制項來裝載在資料行中。

的功能 DataGridColumnStyle 不應與 的 DataColumn 功能混淆。 DataColumn雖然 包含適用于建立資料表架構的屬性和方法, DataGridColumnStyle 但 包含與螢幕上個別資料行外觀相關的屬性和方法。

如果資料列包含 DBNull.Value ,則可以使用 NullText 屬性來設定資料行中顯示的文字。

類別 DataGridColumnStyle 也可讓您在資料變更時指定資料行的行為。 BeginUpdateEndUpdate 方法會在對資料行的資料進行大型更新時暫時暫停資料行的繪圖。 如果沒有這項功能,就會立即繪製方格中每個儲存格中的每個變更;這可能會干擾使用者和效能責任。

數種方法允許監視使用者編輯資料行,包括 EditCommit 事件。

類別的大部分屬性和方法都會量身打造,以控制資料行的外觀。 但有一些 ,例如 GetColumnValueAtRow ,可讓您 SetColumnValueAtRow 檢查並變更指定儲存格中的值。

給實施者的注意事項

當您繼承自 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)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。

(繼承來源 MarshalByRefObject)
Dispose()

釋放 Component 所使用的所有資源。

(繼承來源 Component)
Dispose(Boolean)

釋放 Component 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。

(繼承來源 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()
已淘汰.

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。

(繼承來源 MarshalByRefObject)
GetMinimumHeight()

在衍生類別中覆寫時,取得資料列的最小高度。

GetPreferredHeight(Graphics, Object)

在衍生類別中覆寫時,取得用來自動調整資料行大小的高度。

GetPreferredSize(Graphics, Object)

在衍生類別中覆寫時,取得指定值的寬度和高度。 當使用者使用 DataGridTableStyle 巡覽至 DataGridColumnStyle 時所使用的高度和寬度。

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 控制項,使用者已開始編輯資料行。

適用於

另請參閱