2012-12-31 82 views
0

我正在使用一个相当大的DataGrid绑定到Datatable。我的目标是根据单元格中的数据对单元格组进行着色。基于Datagridview C#中的内容着色组单元格#

我想要datagrid为包含值的所有单元格着色,然后在检测到新值时切换颜色并在整个表格中重复此操作。

以下是对我的工作表中的一个例子:

Contract ID: 
    123456 //Top of the contract, color all cells in the contract blue 
    123456 //blue 
    123456 //blue 
    123456 //blue 
    456789 //New contract, color all these cells green 
    456789 //green 
    456789 //green 
    987654 //Another new contract color all these blue (or another color) again 
    etc... 

我已经试过类似的东西下面,但无济于事...

for (int i = 0; i < myDataGridView.Rows.Count; i++) 
    { 
     if (i > 0) 
     { 
      if (myDataGridView.Rows[i].Cells["contract_id"].Value != myDatagridView.Rows[i-1].Cells["contract_id"].Value) 
      { 
      myDataGridView.CurrentRow.Cells["contract_id"].BackColor = Color.Blue; 
      } 
     } 
    } 

我不知道从哪里开始,我已经尝试循环遍历行并检查值,但这最终会导致性能和速度的崩溃,并且不会给我所寻找的结果。任何建议将不胜感激。

回答

1

如果我正确地理解你的处境,就可以实现你被处理DataGridView.CellValueChanged事件在找什么。这可以防止你必须遍历所有行。理论上,这应该在您填充DGV控件时起作用。

这是我正在谈论的一个非常粗略的例子。您可能需要使用它才能使其适合您的特定情况。在我的情况下,当提交更改的值时,它会调整单元的Style.Backcolor。由于输入数据时可能只有一行,因此我也设置了一个条件来处理这种情况。

如果这是Winforms DGV控件,则需要在代码中使用Cell.Style.BackColor属性,而不是Cell.BackColor属性(Winforms DGV中不存在该属性)。

您将不得不细化代码以适合您的情况。 。 。

private void Form1_Load(object sender, EventArgs e) 
    { 
     // Add a handler for the cell value changed event: 
     this.myDataGridView.CellValueChanged += new DataGridViewCellEventHandler(myDataGridView_CellValueChanged); 
    } 

    void myDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e) 
    { 
     // grab a reference to the changed cell: 
     DataGridViewCell cell = myDataGridView.Rows[e.RowIndex].Cells["contract_id"]; 

     // Guard against the case where this is the first row in the DGV table: 
     if (cell.RowIndex - 1 >= 0) 
     { 
      if (cell.Value != myDataGridView.Rows[cell.RowIndex - 1].Cells["contract_id"].Value) 
      { 
       // CHange the Style.BackColor property for the cell: 
       myDataGridView.CurrentRow.Cells["contract_id"].Style.BackColor = Color.Blue; 
      } 
     } 
0

由于数据库中没有此颜色标志,因此最终您的唯一选择是循环显示数据表行。

我建议你添加一个新的datacolumn到你现有的数据表中,通过它循环并设置你的颜色。

然后,您可以着色“CellFormating”事件中的单元格。在这种情况下,您可以读取颜色列的值并使用它。

还有这里的cellformating事件的完整而简单的例子: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellformatting.aspx

问候

+0

请记住,您可以使用DataGridViewRow.DataBoundItem属性访问“当前”数据行。您可以通过yourDataGridView1.Rows [e.RowIndex]获取当前的datagridviewrow。 – Luferogo

相关问题