簡體   English   中英

C#DataGridView列的日期時間格式

[英]C# DataGridView date time formatting of a column

我有datagridview填充數據庫中的數據,有些列我在其中有日期和時間“MMddyyyy”和“hhmmss”格式,我想要做的是當datagridview加載時,我想將此格式更改為其他格式比如,dd-MM-yy用於日期和時間hh-mm-ss。 我想知道是否有人可以指導我如何做到這一點。 我無法通過gridview.columns [x] .defaultcellstyle.format =“dd-MM-yy”用上面的方法做到這一點我沒有得到任何錯誤但在gridview上沒有任何改變...

謝謝

注意:我也沒有選擇更改數據庫中的列長度.. :-(沒有語法問題

Microsoft建議您攔截CellFormatting事件(其中DATED是您要重新格式化的列):

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    // If the column is the DATED column, check the
    // value.
    if (this.dataGridView1.Columns[e.ColumnIndex].Name == "DATED")
    {
        ShortFormDateFormat(e);
    }
}

private static void ShortFormDateFormat(DataGridViewCellFormattingEventArgs formatting)
{
    if (formatting.Value != null)
    {
        try
        {
            DateTime theDate = DateTime.Parse(formatting.Value.ToString());
            String dateString = theDate.ToString("dd-MM-yy");    
            formatting.Value = dateString;
            formatting.FormattingApplied = true;
        }
        catch (FormatException)
        {
            // Set to false in case there are other handlers interested trying to
            // format this DataGridViewCellFormattingEventArgs instance.
            formatting.FormattingApplied = false;
        }
    }
}

DataGridView格式化中的sintax與DateTime略有不同,但您可以得到相同的結果。 在我的例子中,我有一個Time collumn,默認顯示HH:mm:ss,我想只顯示小時和分鍾:

 yourDataGridView.Columns["Time"].DefaultCellStyle.Format = @"hh\:mm";

暫無
暫無

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

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