2015-12-10 35 views
1

我想改變網格中整行的顏色。網格上方有兩個複選框。一個是活動的,另一個是非活動的。當我點擊活動時,我希望ExpirationDate(網格中的列的名稱)大於或等於今天的所有行DateTime從白色變爲咧嘴。當我點擊不活動,同樣的事情紅色。該過濾器處於活動狀態和非活動狀態正在工作,我只需要更改數據行的顏色。如何在有條件時更改網格中的單元格顏色?

我知道我可以使用cell_formating事件。這是代碼,但我需要一些幫助。

private void grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
    { 
     Color active = Color.LightGreen; 
     Color inactive = Color.LightPink; 

     DataRowView drv = bindingSource[e.RowIndex] as DataRowView; 

     switch (drv["ExpirationDate"].ToString()) 
     { 
      case ???: 
       grid.Rows[e.RowIndex].DefaultCellStyle.BackColor = active; 
       break; 
      case ???: 
       grid.Rows[e.RowIndex].DefaultCellStyle.BackColor = inactive; 
       break; 
     } 
    } 

我不知道我應該放的情況。因爲,C#需要不斷的值。當我把String.Format(" ExpirationDate>= '{0}' ", DateTime.Today)的情況下c#拋出異常「錯誤44預計有一個常量」。任何想法我應該輸入什麼?

+3

由於您需要使用常量情況來執行switch,因此請將其更改爲if語句或else語句。 – krillgar

回答

1

沒有人強迫您使用switch,適當時使用if...else

private void grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    Color active = Color.LightGreen; 
    Color inactive = Color.LightPink; 

    DataRowView drv = bindingSource[e.RowIndex] as DataRowView; 
    bool isActive = drv.Row.Field<DateTime>("ExpirationDate").Date >= DateTime.Today; 
    grid.Rows[e.RowIndex].DefaultCellStyle.BackColor = isActive ? active : inactive; 
} 

我還使用了DataRow擴展方法Field對象轉換爲正確的類型DateTime而不是轉換到string這可能會導致定位:但是在這種情況下,你可以使用條件運算符簡化代碼的問題。

+0

Tnx,這就是我需要的...... :) – Nemanja

1

我會用一個bool,先做檢查,然後再做if-else。它更可讀,更清晰地表達你的意圖。

private void grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    Color active = Color.LightGreen; 
    Color inactive = Color.LightPink; 

    DataRowView drv = bindingSource[e.RowIndex] as DataRowView; 

    bool expired = 
     DateTime.Parse(drv["ExpirationDate"].ToString()) < DateTime.Today; 

    if (expired) 
    { 
     grid.Rows[e.RowIndex].DefaultCellStyle.BackColor = inactive; 
    } 
    else 
    { 
     grid.Rows[e.RowIndex].DefaultCellStyle.BackColor = active; 
    } 

} 
+0

你的方式也是正確的,它與Tim Schmelter的方式非常相似。非常感謝你。 – Nemanja

相關問題