DataGridColumnStyle Klasa

Definicja

Określa wygląd, formatowanie tekstu i zachowanie kolumny sterującej DataGrid . Ta klasa jest abstrakcyjna.

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
Dziedziczenie
DataGridColumnStyle
Pochodne
Implementuje

Przykłady

Poniższy przykład kodu tworzy kontrolkę DataGridColumnStyle , która hostuje kontrolkę 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

Uwagi

Dostęp do kolekcji DataGridColumnStyle obiektów () GridColumnStylesCollectionjest uzyskiwany za pośrednictwem System.Windows.Forms.DataGrid właściwości kontrolki TableStyles .

Kontrolka System.Windows.Forms.DataGrid automatycznie tworzy kolekcję DataGridColumnStyle obiektów podczas ustawiania DataSource właściwości na odpowiednie źródło danych. Utworzone obiekty są wystąpieniami jednej z następujących klas, które dziedziczą z DataGridColumnStyleklasy : DataGridBoolColumn lub DataGridTextBoxColumn .

Aby sformatować wyświetlanie danych, ustaw Format właściwość DataGridTextBoxColumn klasy na jedną z wartości formatowania. Aby uzyskać więcej informacji na temat prawidłowych wartości formatowania, zobacz Formatowanie typówi niestandardowych ciągów formatu daty i godziny.

Możesz również utworzyć własny zestaw DataGridColumnStyle obiektów i dodać je do obiektu GridColumnStylesCollection. W tym celu należy ustawić MappingName styl każdej kolumny na ColumnName element , DataColumn aby zsynchronizować wyświetlanie kolumn z rzeczywistymi danymi.

Przestroga

Zawsze twórz DataGridColumnStyle obiekty i dodawaj je do GridColumnStylesCollection obiektu przed dodaniem DataGridTableStyle obiektów do obiektu GridTableStylesCollection. Po dodaniu pustej DataGridTableStyleMappingName wartości do kolekcji DataGridColumnStyle obiekty są generowane automatycznie. W związku z tym wyjątek zostanie zgłoszony, jeśli spróbujesz dodać nowe DataGridColumnStyle obiekty z zduplikowanymi MappingName wartościami do obiektu GridColumnStylesCollection.

Gdy jedna z klas pochodnych jest tworzona przez kontrolkę System.Windows.Forms.DataGrid , utworzona klasa zależy od DataType klasy skojarzonej DataColumn z obiektem DataGridColumnStyle . Na przykład element DataColumn z ustawionym na System.Boolean wartość zostanie skojarzony z elementem DataGridBoolColumnDataType . Aby określić typ dowolnego DataGridColumnStyleelementu , użyj GetType metody .

Aby utworzyć własne klasy kolumn, można dziedziczyć z DataGridColumnStyleklasy . Możesz to zrobić, aby utworzyć specjalne kolumny, które hostują kontrolki, jak pokazano w DataGridTextBox klasie, która hostuje kontrolkę TextBox . Na przykład możesz hostować kontrolkę Image , aby pokazać obrazy w kolumnach lub utworzyć własną kontrolkę użytkownika do hostowania w kolumnie.

Funkcjonalność obiektu DataGridColumnStyle nie powinna być mylona z funkcją DataColumn. Element DataColumn zawiera właściwości i metody odpowiednie do utworzenia schematu tabeli danych, zawiera DataGridColumnStyle właściwości i metody związane z wyglądem pojedynczej kolumny na ekranie.

Jeśli wiersz zawiera element DBNull.Value, tekst wyświetlany w kolumnie można ustawić za pomocą NullText właściwości .

Klasa DataGridColumnStyle umożliwia również określenie zachowania kolumny podczas zmieniania jej danych. Metody BeginUpdate i EndUpdate tymczasowo wstrzymują rysunek kolumny, podczas gdy duże aktualizacje są wprowadzane do danych kolumny. Bez tej funkcjonalności każda zmiana w każdej komórce siatki zostanie natychmiast narysowana; może to rozpraszać uwagę użytkownika i ponosić odpowiedzialność za wydajność.

Kilka metod umożliwia monitorowanie kolumny podczas jej edytowania przez użytkownika, w tym zdarzenia Edit i Commit .

Większość właściwości i metod klasy jest dostosowana do kontrolowania wyglądu kolumny. Ale kilka, takich jak GetColumnValueAtRow i SetColumnValueAtRow pozwala zbadać i zmienić wartość w określonej komórce.

Uwagi dotyczące implementowania

Po dziedziczeniu z DataGridColumnStyleprogramu należy zastąpić następujące elementy członkowskie: Abort(Int32), , Commit(CurrencyManager, Int32)Edit(CurrencyManager, Int32, Rectangle, Boolean)i Paint(Graphics, Rectangle, CurrencyManager, Int32) (dwa razy).

Konstruktory

DataGridColumnStyle()

W klasie pochodnej inicjuje nowe wystąpienie DataGridColumnStyle klasy.

DataGridColumnStyle(PropertyDescriptor)

Inicjuje DataGridColumnStyle nowe wystąpienie klasy o określonej wartości PropertyDescriptor.

Właściwości

Alignment

Pobiera lub ustawia wyrównanie tekstu w kolumnie.

CanRaiseEvents

Pobiera wartość wskazującą, czy składnik może zgłosić zdarzenie.

(Odziedziczone po Component)
Container

Pobiera element IContainer zawierający element Component.

(Odziedziczone po Component)
DataGridTableStyle

Pobiera element DataGridTableStyle dla kolumny.

DesignMode

Pobiera wartość wskazującą, czy Component element jest obecnie w trybie projektowania.

(Odziedziczone po Component)
Events

Pobiera listę programów obsługi zdarzeń dołączonych do tego Componentelementu .

(Odziedziczone po Component)
FontHeight

Pobiera wysokość czcionki kolumny.

HeaderAccessibleObject

Pobiera element AccessibleObject dla kolumny.

HeaderText

Pobiera lub ustawia tekst nagłówka kolumny.

MappingName

Pobiera lub ustawia nazwę elementu członkowskiego danych, aby zamapować styl kolumny na.

NullText

Pobiera lub ustawia tekst wyświetlany, gdy kolumna zawiera nullelement .

PropertyDescriptor

Pobiera lub ustawia PropertyDescriptor element określający atrybuty danych wyświetlanych przez DataGridColumnStyleelement .

ReadOnly

Pobiera lub ustawia wartość wskazującą, czy dane w kolumnie można edytować.

Site

Pobiera lub ustawia ISite element .Component

(Odziedziczone po Component)
Width

Pobiera lub ustawia szerokość kolumny.

Metody

Abort(Int32)

Po zastąpieniu klasy pochodnej inicjuje żądanie przerwania procedury edycji.

BeginUpdate()

Zawiesza obraz kolumny do momentu EndUpdate() wywołania metody .

CheckValidDataSource(CurrencyManager)

Zgłasza wyjątek, jeśli DataGrid nie ma prawidłowego źródła danych lub jeśli ta kolumna nie jest mapowana na prawidłową właściwość w źródle danych.

ColumnStartedEditing(Control)

Informuje DataGrid użytkownika o rozpoczęciu edytowania kolumny.

Commit(CurrencyManager, Int32)

Po przesłonięcia w klasie pochodnej inicjuje żądanie ukończenia procedury edycji.

ConcedeFocus()

Powiadamia kolumnę, że musi ona zrezygnować z fokusu do kontrolki, którą hostuje.

CreateHeaderAccessibleObject()

Pobiera element AccessibleObject dla kolumny.

CreateObjRef(Type)

Tworzy obiekt zawierający wszystkie istotne informacje wymagane do wygenerowania serwera proxy używanego do komunikowania się z obiektem zdalnym.

(Odziedziczone po MarshalByRefObject)
Dispose()

Zwalnia wszelkie zasoby używane przez element Component.

(Odziedziczone po Component)
Dispose(Boolean)

Zwalnia zasoby niezarządzane używane przez element Component i opcjonalnie zwalnia zasoby zarządzane.

(Odziedziczone po Component)
Edit(CurrencyManager, Int32, Rectangle, Boolean)

Przygotowuje komórkę do edycji.

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

Przygotowuje komórkę do edycji przy użyciu określonego CurrencyManager, numeru wiersza i Rectangle parametrów.

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

Gdy zastąpisz klasę wyprowadzającą, przygotowuje komórkę do edycji.

EndUpdate()

Wznawia malowanie kolumn zawieszonych przez wywołanie BeginUpdate() metody .

EnterNullValue()

Wprowadza wartość Value w kolumnie .

Equals(Object)

Określa, czy dany obiekt jest taki sam, jak bieżący obiekt.

(Odziedziczone po Object)
GetColumnValueAtRow(CurrencyManager, Int32)

Pobiera wartość w określonym wierszu z określonego CurrencyManager.

GetHashCode()

Służy jako domyślna funkcja skrótu.

(Odziedziczone po Object)
GetLifetimeService()
Przestarzałe.

Pobiera bieżący obiekt usługi okresu istnienia, który kontroluje zasady okresu istnienia dla tego wystąpienia.

(Odziedziczone po MarshalByRefObject)
GetMinimumHeight()

Gdy zastąpisz klasę pochodną, pobiera minimalną wysokość wiersza.

GetPreferredHeight(Graphics, Object)

Gdy zastąpisz klasę pochodną, pobiera wysokość używaną do automatycznego zmieniania rozmiaru kolumn.

GetPreferredSize(Graphics, Object)

Po zastąpieniu klasy pochodnej pobiera szerokość i wysokość określonej wartości. Szerokość i wysokość są używane, gdy użytkownik przechodzi do DataGridTableStyle metody .DataGridColumnStyle

GetService(Type)

Zwraca obiekt reprezentujący usługę dostarczaną przez Component obiekt lub przez obiekt Container.

(Odziedziczone po Component)
GetType()

Type Pobiera bieżące wystąpienie.

(Odziedziczone po Object)
InitializeLifetimeService()
Przestarzałe.

Uzyskuje obiekt usługi okresu istnienia, aby kontrolować zasady okresu istnienia dla tego wystąpienia.

(Odziedziczone po MarshalByRefObject)
Invalidate()

Ponownie rysuje kolumnę i powoduje wysłanie komunikatu farby do kontrolki.

MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
MemberwiseClone(Boolean)

Tworzy płytkią kopię bieżącego MarshalByRefObject obiektu.

(Odziedziczone po MarshalByRefObject)
Paint(Graphics, Rectangle, CurrencyManager, Int32)

Maluje element DataGridColumnStyle o określonej Graphicsliczbie , Rectangle, CurrencyManageri wiersza.

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

W przypadku przesłonięcia w klasie pochodnej maluje element DataGridColumnStyle o określonej Graphicswartości , , Rectangle, CurrencyManagernumer wiersza i wyrównanie.

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

Maluje element DataGridColumnStyle o określonym Graphicsnumerze , , Rectangle, CurrencyManagernumer wiersza, kolor tła, kolor pierwszego planu i wyrównanie.

ReleaseHostedControl()

Zezwala kolumnie na zwalnianie zasobów, gdy kontrolka, która jest hostem, nie jest potrzebna.

ResetHeaderText()

Resetuje wartość domyślną HeaderText , null.

SetColumnValueAtRow(CurrencyManager, Int32, Object)

Ustawia wartość w określonym wierszu z wartością z określonej CurrencyManagerwartości .

SetDataGrid(DataGrid)

Ustawia kontrolkę DataGrid , do którą należy ta kolumna.

SetDataGridInColumn(DataGrid)

Ustawia dla DataGrid kolumny .

ToString()

Zwraca wartość String zawierającą nazwę Componentobiektu , jeśli istnieje. Ta metoda nie powinna być zastępowana.

(Odziedziczone po Component)
UpdateUI(CurrencyManager, Int32, String)

Aktualizacje wartość określonego wiersza z danym tekstem.

Zdarzenia

AlignmentChanged

Występuje, gdy Alignment wartość właściwości ulegnie zmianie.

Disposed

Występuje, gdy składnik jest usuwany przez wywołanie Dispose() metody .

(Odziedziczone po Component)
FontChanged

Występuje, gdy czcionka kolumny ulegnie zmianie.

HeaderTextChanged

Występuje, gdy HeaderText wartość właściwości ulegnie zmianie.

MappingNameChanged

Występuje, gdy MappingName wartość się zmienia.

NullTextChanged

Występuje, gdy NullText wartość się zmienia.

PropertyDescriptorChanged

Występuje, gdy PropertyDescriptor wartość właściwości ulegnie zmianie.

ReadOnlyChanged

Występuje, gdy ReadOnly wartość właściwości ulegnie zmianie.

WidthChanged

Występuje, gdy Width wartość właściwości ulegnie zmianie.

Jawne implementacje interfejsu

IDataGridColumnStyleEditingNotificationService.ColumnStartedEditing(Control)

Informuje kontrolkę DataGrid , że użytkownik zaczął edytować kolumnę.

Dotyczy

Zobacz też