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 컬렉션()GridColumnStylesCollection은 컨트롤의 TableStyles 속성을 통해 System.Windows.Forms.DataGrid 액세스됩니다.

컨트롤은 System.Windows.Forms.DataGrid 속성을 적절한 데이터 원본으로 설정할 DataSource 때 자동으로 개체 컬렉션을 DataGridColumnStyle 만듭니다. 실제로 만든 개체는 또는 클래스에서 DataGridColumnStyleDataGridBoolColumnDataGridTextBoxColumn 상속되는 다음 클래스 중 하나의 인스턴스입니다.

데이터 표시의 서식을 지정하려면 클래스의 DataGridTextBoxColumn 속성을 서식 값 중 하나로 설정합니다Format. 유효한 서식 값에 대한 자세한 내용은 형식 서식 지정 및 사용자 지정 날짜 및 시간 서식 문자열을 참조하세요.

고유한 개체 집합 DataGridColumnStyle 을 만들고 에 추가할 수도 있습니다 GridColumnStylesCollection. 이렇게 하면 열 표시를 MappingName 실제 데이터와 동기화하려면 각 열 스타일의 ColumnName 를 의 DataColumn 로 설정해야 합니다.

주의

개체를 에 추가하기 전에 항상 개체GridTableStylesCollectionGridColumnStylesCollection 만들고 DataGridColumnStyle 에 추가 DataGridTableStyle 합니다. 컬렉션 DataGridColumnStyle 에 유효한 MappingName 값이 있는 빈 DataGridTableStyle 을 추가하면 개체가 자동으로 생성됩니다. 따라서 중복 MappingName 값이 있는 새 DataGridColumnStyle 개체를 에 추가하려고 하면 예외가 GridColumnStylesCollectionthrow됩니다.

파생 클래스 중 하나가 컨트롤에 의해 System.Windows.Forms.DataGrid 인스턴스화되면 생성된 클래스는 개체와 DataGridColumnStyle 연결된 의 DataColumnDataType 따라 달라집니다. 예를 들어 가 DataColumnDataType 로 설정된 System.Boolean 은 와 DataGridBoolColumn연결됩니다. 의 형식 DataGridColumnStyle을 확인하려면 메서드를 GetType 사용합니다.

고유한 열 클래스를 만들려면 에서 DataGridColumnStyle상속할 수 있습니다. 컨트롤을 호스트하는 클래스를 예로 DataGridTextBox 들어 컨트롤을 호스트하는 특수 열을 만들기 위해 이 작업을 수행할 수 있습니다 TextBox . 예를 들어 컨트롤을 Image 호스트하여 그림을 열에 표시하거나 열에서 호스트할 사용자 정의 컨트롤을 만들 수 있습니다.

의 기능은 의 DataGridColumnStyle 기능과 DataColumn혼동해서는 안 됩니다. 는 데이터 테이블의 스키마를 만드는 데 적합한 속성과 메서드를 포함하는 반면 DataColumn , DataGridColumnStyle 에는 화면의 개별 열 모양과 관련된 속성과 메서드가 포함됩니다.

행에 가 DBNull.Value포함된 경우 열에 표시된 텍스트를 속성으로 NullText 설정할 수 있습니다.

DataGridColumnStyle 또한 클래스를 사용하면 데이터가 변경되는 동안 열의 동작을 지정할 수 있습니다. 및 EndUpdate 메서드는 BeginUpdate 열의 데이터에 대한 대규모 업데이트가 이루어지는 동안 열 그리기를 일시적으로 일시 중단합니다. 이 기능이 없으면 그리드의 모든 셀에서 모든 변경 내용이 즉시 그려집니다. 이는 사용자에게 방해가 될 수 있으며 성능 책임이 있습니다.

및 이벤트를 포함하여 사용자가 편집할 때 여러 메서드를 사용하여 열을 모니터링할 EditCommit 수 있습니다.

클래스의 대부분의 속성과 메서드는 열의 모양을 제어하는 데 맞게 조정됩니다. 그러나 및 SetColumnValueAtRow 와 같은 GetColumnValueAtRow 몇 가지 를 사용하면 지정된 셀의 값을 검사하고 변경할 수 있습니다.

구현자 참고

에서 DataGridColumnStyle상속하는 경우 , , Commit(CurrencyManager, Int32)Edit(CurrencyManager, Int32, Rectangle, Boolean)Paint(Graphics, Rectangle, CurrencyManager, Int32) (두 번) 멤버Abort(Int32)를 재정의해야 합니다.

생성자

DataGridColumnStyle()

파생 클래스에서 DataGridColumnStyle 클래스의 새 인스턴스를 초기화합니다.

DataGridColumnStyle(PropertyDescriptor)

지정된 DataGridColumnStyle를 사용하여 PropertyDescriptor 클래스의 새 인스턴스를 초기화합니다.

속성

Alignment

열의 텍스트 맞춤을 가져오거나 설정합니다.

CanRaiseEvents

구성 요소가 이벤트를 발생시킬 수 있는지 여부를 나타내는 값을 가져옵니다.

(다음에서 상속됨 Component)
Container

IContainer을 포함하는 Component를 가져옵니다.

(다음에서 상속됨 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의 데이터 소스가 올바르지 않거나 이 열이 데이터 소스의 올바른 속성에 매핑되지 않으면 예외가 throw됩니다.

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)

파생 클래스에서 재정의된 경우 지정한 값의 너비와 높이를 가져옵니다. 너비와 높이는 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)

지정한 DataGridColumnStyle, Graphics, Rectangle 및 행 번호를 사용하여 CurrencyManager을 그립니다.

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

파생 클래스에서 재정의된 경우 지정한 DataGridColumnStyle, Graphics, Rectangle, 행 번호 및 맞춤을 사용하여 CurrencyManager을 그립니다.

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

지정한 DataGridColumnStyle, Graphics, Rectangle, 행 번호, 배경색, 전경색 및 맞춤을 사용하여 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 컨트롤에 알립니다.

적용 대상

추가 정보