VB.NET 2008/VB - 데이터 그리드 뷰

데이터 그리드 뷰에서 DateTimePicker 컨트롤을 표시하는 방법

본클라쓰 2012. 9. 25. 11:52

 

데이터그리드뷰 컨트롤은 사용자가 다양한 방법으로 값을 입력하고 편집할 수 있는 여러 열 형식을 제공합니다. 이러한 열 형식이 데이터 입력 요구 사항을 만족하지 않아도 선택한 컨트롤을 호스트하는 셀로 고유한 열 형식을 만들 수 있습니다. 이렇게 하려면 DataGridViewColumn 및 DataGridViewCell에서 파생되는 클래스를 정의해야 합니다. 또한 Control에서 파생되고 IDataGridViewEditingControl 인터페이스를 구현하는 클래스를 정의해야 합니다.

 

자료출처) http://msdn.microsoft.com/ko-kr/library/7tas5c80(v=vs.90).aspx#Y289

 

 

다음 예제 코드는 DateTimePicker를 사용하여 셀의 편집모드를 구현한 데이터 그리드 뷰이다. 사용자 지정 형식의 컬럼을 만들기 위해서는 IDataGridViewEditingControl 구현, Cell 구현, Column 구현 순으로 이루어진다.

 

 

 

1) IDataGridViewEditingControl 구현

 

   편집모드를 DateTimePicker 컨트롤 형식으로 지정하기 위해 DateTimePicker를 상속한다.

 

Public Class CalendarEditingControl
    Inherits DateTimePicker
    Implements IDataGridViewEditingControl

 

    Private dataGridViewControl As DataGridView
    Private valueIsChanged As Boolean = False
    Private rowIndexNum As Integer

 

 

    Public Sub New()
        Me.Format = DateTimePickerFormat.Short
    End Sub

 

 

    Public Property EditingControlFormattedValue() As Object _
        Implements IDataGridViewEditingControl.EditingControlFormattedValue

        Get
            Return Me.Value.ToShortDateString()
        End Get

        Set(ByVal value As Object)
            If TypeOf value Is String Then
                Me.Value = DateTime.Parse(CStr(value))
            End If
        End Set

    End Property

 

 

    Public Function GetEditingControlFormattedValue(ByVal context _
        As DataGridViewDataErrorContexts) As Object _
        Implements IDataGridViewEditingControl.GetEditingControlFormattedValue

        Return Me.Value.ToShortDateString()

    End Function

 

 

    Public Sub ApplyCellStyleToEditingControl(ByVal dataGridViewCellStyle As  _
        DataGridViewCellStyle) _
        Implements IDataGridViewEditingControl.ApplyCellStyleToEditingControl

        Me.Font = dataGridViewCellStyle.Font
        Me.CalendarForeColor = dataGridViewCellStyle.ForeColor
        Me.CalendarMonthBackground = dataGridViewCellStyle.BackColor

    End Sub

 

 

    Public Property EditingControlRowIndex() As Integer _
        Implements IDataGridViewEditingControl.EditingControlRowIndex

        Get
            Return
rowIndexNum
        End Get
        Set
(ByVal value As Integer)
            rowIndexNum = value
        End Set

    End Property

 

 

    Public Function EditingControlWantsInputKey(ByVal key As Keys, _
        ByVal dataGridViewWantsInputKey As Boolean) As Boolean _
        Implements IDataGridViewEditingControl.EditingControlWantsInputKey

        ' Let the DateTimePicker handle the keys listed.
        Select Case key And Keys.KeyCode
            Case Keys.Left, Keys.Up, Keys.Down, Keys.Right, _
                Keys.Home, Keys.End, Keys.PageDown, Keys.PageUp

                Return True

            Case Else
                Return Not dataGridViewWantsInputKey
        End Select

    End Function

 

 

    Public Sub PrepareEditingControlForEdit(ByVal selectAll As Boolean) _
        Implements IDataGridViewEditingControl.PrepareEditingControlForEdit

        ' No preparation needs to be done.

    End Sub

    Public ReadOnly Property RepositionEditingControlOnValueChange() _
        As Boolean Implements _
        IDataGridViewEditingControl.RepositionEditingControlOnValueChange

        Get
            Return False
        End Get

    End Property

 

 

    Public Property EditingControlDataGridView() As DataGridView _
        Implements IDataGridViewEditingControl.EditingControlDataGridView

        Get
            Return
dataGridViewControl
        End Get
        Set
(ByVal value As DataGridView)
            dataGridViewControl = value
        End Set

    End Property

 

 

    Public Property EditingControlValueChanged() As Boolean _
        Implements IDataGridViewEditingControl.EditingControlValueChanged

        Get
            Return
valueIsChanged
        End Get
        Set
(ByVal value As Boolean)
            valueIsChanged = value
        End Set

    End Property

 

 

    Public ReadOnly Property EditingControlCursor() As Cursor _
        Implements IDataGridViewEditingControl.EditingPanelCursor

        Get
            Return
MyBase.Cursor
        End Get

    End Property

 

 

    Protected Overrides Sub onValueChanged(ByVal eventargs As EventArgs)

        ' Notify the DataGridView that the contents of the cell have changed.
        valueIsChanged = True
        Me.EditingControlDataGridView.NotifyCurrentCellDirty(True)
        MyBase.OnValueChanged(eventargs)

    End Sub

End Class

 

 

2) CalendarCell 구현

 

이 셀은 일반 텍스트 상자 셀에 날짜를 표시하지만 사용자가 셀을 편집하면 DateTimePicker 컨트롤이 표시된다. 텍스트 상자 표시 기능이 다시 구현되지 않도록 하기 위해 CalendarCell 클래스는 DataGridViewCell 클래스에서 직접 상속되지 않고 DataGridViewTextBoxCell 클래스에서 파생된다.

 

Public Class CalendarCell
    Inherits DataGridViewTextBoxCell

 

 

    Public Sub New()
        ' Use the short date format.
        Me.Style.Format = "d"
    End Sub

   

 

   Public Overrides Sub InitializeEditingControl(ByVal rowIndex As Integer, _
        ByVal initialFormattedValue As Object, _
        ByVal dataGridViewCellStyle As DataGridViewCellStyle)

 

        ' Set the value of the editing control to the current cell value.
        MyBase.InitializeEditingControl(rowIndex, initialFormattedValue, _
            dataGridViewCellStyle)

        Dim ctl As CalendarEditingControl = _
            CType(DataGridView.EditingControl, CalendarEditingControl)
        ctl.Value = CType(Me.Value, DateTime)

    End Sub

 

 

    Public Overrides ReadOnly Property EditType() As Type
        Get
            ' Return the type of the editing contol that CalendarCell uses.
            Return GetType(CalendarEditingControl)
        End Get
    End Property

 

 

    Public Overrides ReadOnly Property ValueType() As Type
        Get
            ' Return the type of the value that CalendarCell contains.
            Return GetType(DateTime)
        End Get
    End Property

 

 

    Public Overrides ReadOnly Property DefaultNewRowValue() As Object
        Get
            ' Use the current date and time as the default value.
            Return DateTime.Now
        End Get
    End Property
End Class

 

 

3) 마지막으로 컬럼을 구현합니다.

Public Class CalendarColumn
    Inherits DataGridViewColumn


    Public Sub New()
        MyBase.New(New CalendarCell())
    End Sub

 

 

    Public Overrides Property CellTemplate() As DataGridViewCell
        Get
            Return
MyBase.CellTemplate
        End Get
        Set
(ByVal value As DataGridViewCell)

            ' Ensure that the cell used for the template is a CalendarCell.
            If (value IsNot Nothing) AndAlso _
                Not value.GetType().IsAssignableFrom(GetType(CalendarCell)) _
                Then
               
Throw New InvalidCastException("Must be a CalendarCell")
            End If
            MyBase.CellTemplate = value

        End Set
    End Property

 

End Class