2017-02-18 61 views
0

我已經從sql數據庫動態加載數據網格視圖。在那根據特定的列值,我必須改變單元格的背景顏色。Datagrid在Windows C#應用程序中查看單元格格式問題

enter image description here

但顯示這樣的,

private void Grid_Log_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
     { 
      // Set the background to red for negative values in the Balance column. 
      if (Grid_Log.Columns[e.ColumnIndex].Name.Equals("MStatus") || Grid_Log.Columns[e.ColumnIndex].Name.Equals("Status")) 
      { 
       if (e.Value.Equals("SUCCESS")||e.Value.Equals("Closed")) 
       { 
        //e.CellStyle.BackColor = Color.Red; 
        //e.CellStyle.SelectionBackColor = Color.DarkRed; 
        //Grid_Log.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Red; 
        Grid_Log.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red; 
       } 
      } 
     } 

我上面代碼嘗試,但仍然出現了。

+0

我想你應該看看這個:HTTP://stackoverflow.com/questions/26994457/c-sharp-red-cross-in-datagridview –

+0

您發佈的代碼將背景顏色變爲紅色如果「MStatus」值爲「SUCCESS」,或者如果「Status」值爲「Closed」,則背景將變爲紅色。你應該檢查'e.Value'可能爲空的可能性。我不確定圖片應該代表什麼,單元格或整個網格? – JohnG

+0

謝謝johnG,我修復了它,當e.Value爲null時發生。 – Karthik

回答

0
private void Grid_Log_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
     { 
      if (Grid_Log.Columns[e.ColumnIndex].Name.Equals("MStatus") || Grid_Log.Columns[e.ColumnIndex].Name.Equals("Status")) 
      { 
       if (e.Value!=null) 
       { 
        if (e.Value.Equals("SUCCESS") || e.Value.Equals("Closed")) 
        { 
         //e.CellStyle.BackColor = Color.Red; 
         //e.CellStyle.SelectionBackColor = Color.DarkRed; 
         //Grid_Log.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Red; 
         Grid_Log.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red; 
        } 
       } 
      } 
     } 
相關問題