3

データベースからデータを入力するdatagridviewがあり、日付と時刻が「MMddyyyy」と「hhmmss」の形式である列があります。datagridviewが読み込まれたときに、この形式を他の形式に変更したいと思います。たとえば、日付と時刻hh-mm-ssの場合はdd-MM-yyです。誰かが私にそれをする方法を教えてくれるかどうか疑問に思いました。gridview.columns [x] .defaultcellstyle.format = "dd-MM-yy"でこれを行うことができませんでした。エラーは発生しませんが、gridviewでは何も変更されません...

ありがとう

注:データベースの列の長さも変更するオプションはありません。..:-(構文の問題はありません

4

2 に答える 2

9

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;
        }
    }
}
于 2012-05-17T23:28:40.063 に答える
2

DataGridView の書式設定の構文は、DateTime の場合とは少し異なりますが、同じ結果を得ることができます。私の例では、デフォルトで HH:mm:ss を表示する Time 列があり、時間と分のみを表示したい:

 yourDataGridView.Columns["Time"].DefaultCellStyle.Format = @"hh\:mm";
于 2014-03-27T14:53:59.927 に答える