繁体   English   中英

如何在C#中获取datagridview的单元格状态

[英]How to get the cell state of datagridview in C#

我有一个datagridview,dgv1有10列C#表单,它有一个DB表。 第二列是一个组合框,其值为close / open /供考虑....用户可以修改任何单元格中的值。 修改完成后,用户可以按“保存”按钮将更改保存到数据库表。 但是在保存更改之前还需要完成另一项任务:如果任何第二列的值发生更改,则必须调用DB存储过程。

我的问题是我不知道如何判断单元格的值是否发生了变化,而且我还需要知道以前的值,先前和当前值必须传递给存储过程。

foreach (DataRow rows in dtList.Rows)
{
   if(rows.RowState.ToString() == "Modified")
   {
      if(rows.cell(1) is changed)
      { 
         call stored procedure here... 
      }
    }
    i++;
}

一个简单的(但可能不是最好的方法!)将使用List来存储ComboBox值。在表单加载时我们可以写:

const int yourCell = 1;
List<string> colComboValues = new List<string>();
foreach (DataGridViewRow dgvRow in this.dataGridView.Rows)
{
    DataGridViewComboBoxCell CB = dgvRow.Cells[yourCell] as DataGridViewComboBoxCell;
    colComboValues.Add(CB.Value.ToString());
}

然后在保存时我们可以使用以下方法检查哪些ComboBox已更改:

// On Save.
int nIdx = 0;
foreach (DataGridViewRow dgvRow in this.dataGridView.Rows)
{
    DataGridViewComboBoxCell CB = dgvRow.Cells[yourCell] as DataGridViewComboBoxCell;
    if (String.Compare(CB.Value.ToString(), colComboValues[nIdx++], false) != 0)
    {
        // Value has changed!
    }
    else
    {
        // Value has not.
    }
}

希望这可以帮助。

如果您订阅了CellBeginEdit和CellEndEdit事件并将结果添加到字典中(如果有更改),最终结果就是您只是遍历字典,该字典将包含单元格作为其键和(在我的情况下,对象在您的case combobox values)编辑前的前一个值。

    Dictionary<DataGridViewCell, object> cvDict = new Dictionary<DataGridViewCell, object>();

    private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
    {
        DataGridViewCell dgcv = (sender as DataGridView).Rows[e.RowIndex].Cells[e.ColumnIndex];
        if (!cvDict.ContainsKey(dgcv))
        {
            cvDict.Add(dgcv, dgcv.Value);
        }
    }

    private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        DataGridViewCell dgcv = (sender as DataGridView).Rows[e.RowIndex].Cells[e.ColumnIndex];
        if (cvDict.ContainsKey(dgcv))
        {
            if (cvDict[dgcv].Equals(dgcv.Value))
            {
                cvDict.Remove(dgcv);
            }
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM