2016-07-15 24 views
0

と表示されます。データグリッドビューにデータを設定しています。列の1つは時間(hh:mm:ss)で表示する必要があります。フォーマットDatagridviewの列の時間は、hh:mm:ss

データはAccessデータベースから抽出され、データグラムビューに正常に入力されます。時間として表示する列は、アクセスデータベースに「番号」として設定されます。ご覧のとおり、選択クエリ内で/ 86400を使用して秒数に変換します。

DefaultCellStyle.Format = "hh:mm:ss tt"を使用して列を変換しようとすると、データの列全体が各セルの「hh:mm:ss tt」に置き換えられます。つまり、すべてのセルでhh:mm:ss ttという単なる数字です。

以下は私のコードです - 誰でも私が間違っていることをアドバイスできますか?

string strProvider = 
    "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = P:\\JC_StockFile\\Mitel\\Mitel.accdb"; 
string strSql = 
    "SELECT [MidnightStartDate], [Agent Name], [LoginTime], [LogoutTime], [ShiftDuration]/86400 as ShiftDuration " + 
    "FROM login_data " + 
    "WHERE [MidnightStartDate] > @LeDate"; 

OleDbConnection con = new OleDbConnection(strProvider); 
OleDbCommand cmd = new OleDbCommand(strSql, con); 
con.Open(); 
cmd.CommandType = CommandType.Text; 
cmd.Parameters.AddWithValue("@LeDate", DateTime.Today.AddDays(-3)); 
OleDbDataAdapter da = new OleDbDataAdapter(cmd); 
DataTable scores = new DataTable(); 
da.Fill(scores); 
dataGridView1.DataSource = scores; 
dataGridView1.Columns["ShiftDuration"].DefaultCellStyle.Format = "hh:mm:ss tt"; 
+0

あなたを使用することをお勧め

はこれを試してみてくださいコードはうまくいくはずです。何か他のことが起こっているに違いありません。あなたのデータは本当にDateTimesではないでしょう。 – TaW

+1

私はTaWがここに何かあると思います。 SELECTステートメントの一部としてShiftDuration列をDateTimeにキャストし、その行為があるかどうかを確認してください。 – Overhed

答えて

0

このプロパティは他の文字列形式と同じように動作します。編集:私は実際にあなただけ大文字に問題があると思う:

dataGridView1.Columns["ShiftDuration"].DefaultCellStyle.Format = "HH:mm:ss";

参考: https://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx

+0

ありがとうございました。残念ながら、これは同じ方法で列をフォーマットしましたが、今度は各セルの{0:c}を使用します。 – jamesc100

+0

私の答えを編集しました。レビューしてください。 – Overhed

+0

これはまた、私が恐れているのと同じ方法でセルをフォーマットします。カラム内の各セルの "HH:mm:ss" – jamesc100

0

MicrosoftはCellFormattingイベント

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

private static void ShortFormDateFormat(DataGridViewCellFormattingEventArgs formatting) 
{ 
    if (formatting.Value != null) 
    { 
     try 
     { 
      DateTime theDate = DateTime.Parse(formatting.Value.ToString()); 
      String dateString = theDate.toString("hh:mm:ss tt");  
      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; 
     } 
    } 
} 
+0

ok。私は – SilentCoder

+0

を編集します。こんにちはCodelahiru、答えに感謝します。 'DateTime'に 'toString'の定義がなく、 'DateTime'タイプの最初の引数を受け入れる拡張メソッド 'toString'が見つかりませんでした(見つからない場合があります) using命令やアセンブリ参照?) – jamesc100

+2

それは 'ToString()'でなければなりません.. capital 'T' – SilentCoder

関連する問題