2013-08-30 160 views
0

我有兩個datagridview。 具有相同的列標題但不同的單元格數據。用c中的不同值突出顯示datagridview的單元格#

第一個叫grid_db 第二個是calld grid_statement。

如果grid_db的值與cell [j]上的grid_statement的值不同,我必須使單元格高亮顯示(紅色)。 我嘗試以下

int no_of_col = grid_db.Columns.Count; 
int j; 

for (j = 0; j < no_of_col;) 
{ 
    //if statement value is null replace with ZERO 
    if (grid_statement.Rows[0].Cells[j].Value != null && 
     !string.IsNullOrWhiteSpace(grid_statement.Rows[0].Cells[j].Value.ToString())) 
    { 
     B = grid_statement.Rows[0].Cells[j].Value.ToString(); 
    } 


    //if db value is null replace with zero 
    if (grid_db.Rows[0].Cells[j].Value != null && 
     !string.IsNullOrWhiteSpace(grid_db.Rows[0].Cells[j].Value.ToString())) 
    { 
     A = grid_db.Rows[0].Cells[j].Value.ToString(); 
    } 

    if (A != B) 
    { 
     grid_db.Rows[0].Cells[j].Style.BackColor = Color.Red; 
     grid_statement.Rows[0].Cells[j].Style.BackColor = Color.Red; 

     j++; 
    } 
} 

不過,這並不works.The上面的代碼突出了網格的所有列。 幫助?

回答

0
var differentCells = 
     grid_db.Rows.OfType<DataGridViewRow>() 
        .SelectMany(r=>r.Cells.OfType<DataGridViewCell>()) 
        .Where(c=>!grid_statement[c.ColumnIndex,c.RowIndex].Value.Equals(c.Value)); 
//loop through all the cells and make them red 
foreach(var cell in differentCells) 
    cell.Style.BackColor = Color.Red; 
+0

它適合你嗎?這只是他的代碼的簡化變體。我嘗試了他和你的代碼,但我仍然無法給這些單元格着色。我找不到原因。 –

+0

bahh ..沒有任何結果。他的代碼也將所有單元格繪成紅色。 –

0

我想你的代碼,和它的作品對我來說,我已經改變的唯一事情是在for循環遞增的每次傳球,否則很容易被無限的(它僅適用於第一排,因爲這是你的代碼是幹什麼的):

public Form1() 
    { 
     InitializeComponent(); 

     grid_db.DataSource = new[] 
     { 
      new{ 
       id = 1, 
       tekst="a" 
       }, 
       new 
        { 
         id=2, 
         tekst="b" 
        } 
     }.ToList(); 
     grid_statement.DataSource = new[] 
     { 
      new{ 
       id = 1, 
       tekst="b" 
       }, 
       new 
        { 
         id=2, 
         tekst="c" 
        } 
     }.ToList(); 
     Load += (sender, args) => 
        { 
         HighlightRows(); 
        }; 
    } 
    private void HighlightRows() 
    { 
     int no_of_col = grid_db.Columns.Count; 
     int j; 
     var B = ""; 
     var A = ""; 
     for (j = 0; j < no_of_col; j++) 
     { 
      //if statement value is null replace with ZERO 
      if (grid_statement.Rows[0].Cells[j].Value != null && 
       !string.IsNullOrWhiteSpace(grid_statement.Rows[0].Cells[j].Value.ToString())) 
      { 
       B = grid_statement.Rows[0].Cells[j].Value.ToString(); 
      } 
      //if db value is null replace with zero 
      if (grid_db.Rows[0].Cells[j].Value != null && 
       !string.IsNullOrWhiteSpace(grid_db.Rows[0].Cells[j].Value.ToString())) 
      { 
       A = grid_db.Rows[0].Cells[j].Value.ToString(); 
      } 
      if (A != B) 
      { 
       grid_db.Rows[0].Cells[j].Style.BackColor = Color.Red; 
       grid_statement.Rows[0].Cells[j].Style.BackColor = Color.Red; 

      } 
     } 
    } 
相關問題