2016-11-22 15 views
0

DataGridViewには複数の列があり、そのうちの1つは「較正期限」です。私は行の色を校正期限が過ぎていればREDに、校正期日まで1ヶ月未満であれば青色に変える方法を探しています。列の日付に基づいてDataGridViewの行の色を変更します

私は何もしませんでした次のコードを試してみました:

private void Form1_Load(object sender, EventArgs e) 
{ 
    foreach (DataGridView row in instrumentsDataGridView.Rows) 
    { 
     var now = DateTime.Now; 
     var expirationDate = DateTime.Parse(instrumentsDataGridView.Columns["CalibrationDue"].ToString()); 
     var Month = expirationDate.AddDays(-30); 

     if (now > Month && now < expirationDate) 
      row.DefaultCellStyle.BackColor = Color.Blue; 
     else if (now > expirationDate) 
      row.DefaultCellStyle.BackColor = Color.Red; 
    } 
} 
+0

をいずれも赤と青の色が表示されませんか? –

+0

コードの出力に何かエラーがありますか? –

+0

@JonesJoseph色が表示されず、エラーも表示されませんでした。 – Sanaa

答えて

0

CellFormattingイベントでそれを実行します。

private void DataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    if (e.ColumnIndex == instrumentsDataGridView.Columns["CalibrationDue"].Index) 
    { 
     if (e.Value == null) 
      return; 

     var now = DateTime.Now; 
     var expirationDate = (DateTime)e.Value; 
     var month = expirationDate.AddDays(-30); 

     var row = instrumentsDataGridView.Rows[e.RowIndex]; 

     if (now > month && now < expirationDate) 
      row.DefaultCellStyle.BackColor = Color.Blue; 
     else if (now > expirationDate) 
      row.DefaultCellStyle.BackColor = Color.Red; 
    } 
} 
+0

色がまだ表示されない – Sanaa

+0

@Sanaa CellFormattingイベントハンドラを追加していない場合は、https://msdn.microsoft.com/en-us/library/dd492149.aspxを確認できます。 – Slai

0

あなたはDataGridViewRow.Cellsプロパティを使用することができます。

DateTime now = DateTime.Now, thirtyDaysAgo = now.AddDays(-30), expirationDate; 

foreach (DataGridViewRow row in instrumentsDataGridView.Rows) 
{ 
    string cellText = row.Cells["CalibrationDue"].Value + ""; 

    if (DateTime.TryParse(cellText, out expirationDate)) 
    { 
     if (expirationDate < now) 
      row.DefaultCellStyle.BackColor = Color.Red; 
     else if (expirationDate > thirtyDaysAgo) 
      row.DefaultCellStyle.BackColor = Color.Blue; 
    } 
} 
+0

色。私はおそらく、フォームロード機能ではなく、コードをどこか別の場所に置く必要があると思いますか? – Sanaa

+0

@Sanaa行が追加された後でなければならず、デバッガを使用してカラーステートメントに達しているかどうかを確認することができます。 – Slai

+0

ええ、私は今それを変更して、それは最終的に働いている! – Sanaa

0

私は間違った場所にコードを入れていました。私は別のフォームのソースコード(DataGridViewに詳細情報を入力するためのフォーム)に次のコードを入れたのだが、今取り組んでいる:

DateTime now = DateTime.Now, thirtyDaysAgo = now.AddDays(-30), expirationDate; 

     foreach (DataGridViewRow row in form.instrumentsDataGridView.Rows) 
     { 
      string cellText = row.Cells["CalibrationDue"].Value + ""; 

      if (DateTime.TryParse(cellText, out expirationDate)) 
      { 
       if (expirationDate < now) 
        row.DefaultCellStyle.BackColor = Color.Red; 
       else if (expirationDate > thirtyDaysAgo) 
        row.DefaultCellStyle.BackColor = Color.PaleTurquoise; 
      } 
     } 
関連する問題