如何在datagrid中更改大于零值的单元格颜色

时间:2012-11-07 06:18:27

标签: c# winforms sql-server-2008

enter code here

网格中有两个单元格我希望在输入大于零值的另一个单元格时将一个单元格颜色和值更改为零

< / p>

    private void grdDetail_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        { 
            if (this.IsLoadComplete) 
              { 
                UpdateValueofQtyCell(e.ColumnIndex); 
              } 
       }
  private void UpdateValueofQtyCell(int index)
        {
            int cur_row = grdDetail.CurrentRow.Index;

            if (index == 1)
            {
                grdDetail[1, cur_row].Style.BackColor = Color.White;
                grdDetail[2, cur_row].Style.BackColor = Color.FromArgb(224, 224, 224);
                grdDetail[2, cur_row].Value = 0;
            }
           else  if (index == 1)
            {
                grdDetail[2, cur_row].Style.BackColor = Color.White;
                grdDetail[1 cur_row].Style.BackColor = Color.FromArgb(224, 224, 224);
                grdDetail[1, cur_row].Value = 0;
             }
        }

1 个答案:

答案 0 :(得分:0)

在班级创建以下变量。

bool IsAnyGreaterThanZero = false;

然后首先调用下面的函数,该函数判断任何单元格值是否大于零。

private void CheckForGreaterThanZero()
{
    for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
      {

         if ((int)dataGridView1.Rows[i].Cells[0].Value > 0)
            {
              IsAnyGreaterThanZero = true;
            }
      }
}

然后调用下面的函数来改变那些值等于零的单元格的颜色。

private void ChangeOtherCellColor()
 {
  if(IsAnyGreaterThanZero)
  {
    for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
      {
        if ((int)intdataGridView1.Rows[i].Cells[0].Value == 0)
        {
            DataGridViewCellStyle CellStyle = new DataGridViewCellStyle();
            CellStyle.BackColor = Color.Red;
            dataGridView1.Rows[i].Cells[0].Style = CellStyle;
        }
      }
   }


  }