簡體   English   中英

datagridview將單元格樣式應用於單元格

[英]datagridview apply cellstyle to cells

我使用此示例在winforms應用程序中為DataGridView創建DateTime列。

http://msdn.microsoft.com/en-us/library/7tas5c80.aspx

我可以在Windows窗體設計器中看到新列,並將其添加到現有的DataGridView中。 但是,我希望能夠在設計器中更改“ DefaultCellStyle”時更改顯示格式。

設計器生成的代碼如下所示:

    DataGridViewCellStyle1.Format = "t"
    DataGridViewCellStyle1.NullValue = Nothing
    Me.colDate.DefaultCellStyle = DataGridViewCellStyle1
    Me.colDatum.Name = "colDate"
    Me.colDatum.Resizable = System.Windows.Forms.DataGridViewTriState.[False]

沒關系 但是由於DataGridViewCalendarCell的代碼在構造函數中執行了以下操作:

    Public Sub New()
        Me.Style.Format = "d"
    End Sub

格式永遠不會更改為“ t”(時間格式)。 我沒有找到如何應用所屬列中的格式來使用這種環繞自動櫃員機的方法:

    Public Overrides Function GetInheritedStyle _
            (ByVal inheritedCellStyle As _
                  System.Windows.Forms.DataGridViewCellStyle, _
            ByVal rowIndex As Integer, ByVal includeColors As Boolean) _
    As System.Windows.Forms.DataGridViewCellStyle

        If Me.OwningColumn IsNot Nothing Then
            Me.Style.Format = Me.OwningColumn.DefaultCellStyle.Format
        End If

        Return MyBase.GetInheritedStyle(_
            inheritedCellStyle, rowIndex, includeColors)

    End Function

但是,由於這只是一個hack,所以我想知道將“ DataGridViewColumn”中的默認單元樣式應用於其單元的“應如何做”。 有什么建議么?

我將刪除構造函數。 問題在於構造函數是隱式創建樣式。 因此,將不使用默認樣式的格式。 實際上,這是“資源浪費”,因為每個單元將具有自己的樣式,而不是所有單元都共享相同的樣式。

刪除構造函數將解決您的問題,但是如果您要默認為“短日期”,則最好重寫GetFormattedValue 如下面的例子。 我要強調,這只是一個例子。 您必須弄清楚細節。

    Protected Overrides Function GetFormattedValue( _
        ByVal value As Object, _
        ByVal rowIndex As Integer, _
        ByRef cellStyle As System.Windows.Forms.DataGridViewCellStyle, _
        ByVal valueTypeConverter As System.ComponentModel.TypeConverter, _
        ByVal formattedValueTypeConverter As System.ComponentModel.TypeConverter, _
        ByVal context As System.Windows.Forms.DataGridViewDataErrorContexts) As Object

        If (cellStyle IsNot Nothing) OrElse (String.IsNullOrEmpty(cellStyle.Format)) Then
            'no format specified, so default to short date
            cellStyle.Format = "d"
        End If

        Return MyBase.GetFormattedValue(value, rowIndex, cellStyle, valueTypeConverter, formattedValueTypeConverter, context)

    End Function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM