2013-08-30 122 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; 

      } 
     } 
    } 
相关问题