如果正在编辑单元格,如何更改单元格的背景颜色

时间:2015-06-15 13:06:11

标签: c# winforms datagridview background-color

我有两个datagridview单元格grid1和grid2。我将文件加载到两个网格,我已经使用了该文件的版本。每当我保存/编辑文件时,它会将文件版本从5增加1,这意味着它将是6,7,8,9等。

文件版本从5开始。增加它没有问题

我想更改单元格的背景颜色,如果我加载文件并进行编辑,则从编辑的单元格中,它必须将背景颜色更改为黄色。

  1. 加载现有文件
  2. 编辑文件
  3. 已编辑单元格的背景颜色必须更改为黄色
  4. 保存文件并清除颜色(这是有效的)
  5. 我试过这个,但是,当我创建文件时它会突出显示颜色。我只需要在编辑文件时更改背景单元格颜色。

    我的代码:

        int version_Number = 5;
        string _OriginalValue;
        private void Grid1_CellBeginEdit_1(object sender, DataGridViewCellCancelEventArgs e)
        {
            try
            {
                _OriginalValue = Grid1[e.ColumnIndex, e.RowIndex].Value.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error occured.\nError message: " + ex.Message, "Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    
    
        #region Grid2_CellEndEdit_1
        private void Grid2_CellEndEdit_1(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                DataGridViewCell cell = Grid2[e.ColumnIndex, e.RowIndex];
                if (cell.Value.ToString() != _OriginalValue)
                {
                    if (version_Number >= 1000)
                    {
                        cell.Style.BackColor = Color.Yellow;
                    }
                }   
    

2 个答案:

答案 0 :(得分:0)

You have to handle the part that colors the cell in the cellformating event, a sample i tried is as below

 private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            DataGridViewCell cell = dataGridView1[e.ColumnIndex, e.RowIndex];
            if (cell.Value  != null)
            {
                if (cell.Value.ToString() != _OriginalValue)
                {

                    cell.Style.BackColor = Color.Yellow;

                }   
            }

    }

答案 1 :(得分:0)

您可能希望使用标志来阻止在加载数据期间发生着色:

int version_Number = 5;
string _OriginalValue;

bool loading = false;

你在哪里加载数据;现在设置并重置那里的标志:

loding = true;
yourDataLoadingCodeHere;
loading = false;

现在,如果它们起作用,你可以简单地中止你的两个事件:

private void Grid1_CellBeginEdit_1(object sender, DataGridViewCellCancelEventArgs e)
{
    if (loading) return;

    try
    {
        _OriginalValue = Grid1[e.ColumnIndex, e.RowIndex].Value.ToString();
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error occured.\nError message: " + 
        ex.Message, "Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}



private void Grid2_CellEndEdit_1(object sender, DataGridViewCellEventArgs e)
{
   if (loading) return;

   try
   {
     DataGridViewCell cell = Grid2[e.ColumnIndex, e.RowIndex];
     if (cell.Value.ToString() != _OriginalValue)
     {
        if (version_Number >= 1000)
        {
           cell.Style.BackColor = Color.Yellow;
        }
    }  
    ..
    ..