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

4
我有一个包含10列的C#表单中的数据网格视图,名为dgv1,它与一个数据库表相绑定。第二列是一个下拉框,其值为close/open/for consideration... 用户可以修改任何单元格中的值。修改完成后,用户可以按保存按钮将更改保存到数据库表中。 但在保存更改之前,还需要完成另一个任务:如果任何第二列的值发生了更改,则必须调用一个数据库存储过程。
我的问题是我不知道如何找出单元格的值是否已更改,而且我需要知道先前的值,先前和当前的值都必须传递给存储过程。
foreach (DataRow rows in dtList.Rows)
{
   if(rows.RowState.ToString() == "Modified")
   {
      if(rows.cell(1) is changed)
      { 
         call stored procedure here... 
      }
    }
    i++;
}

WinForms、WPF等?您可以在窗体(假设为WinForms)初始化/加载时,将DataGridView的数据存储在DataTable中。然后,在按下“保存”按钮时(与绑定的DataTable相比),检查更改。 - MoonKnight
KillerCam提出了一个很好的建议,另一种方式是将值存储在HashTable中,就像在DB方面进行内联Delta一样,如果您熟悉有关DB的Delta术语...如果这是Oracle,则完全容易,因为您可以获得:Old和:New..现在我想起来了..为什么不在On RoW Click事件中捕获当前值..并且无论他们在哪一行,都捕获当前状态..并且它改变时也捕获它,然后比较将它们存储在属性中.. - MethodMan
2个回答

0
一个简单的(但可能不是最好的方法!)是使用一个 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.
    }
}

希望这能有所帮助。

非常感谢大家的建议!我将首先尝试Killercam的建议。再次感谢! - Robert Lacasse

0
如果您订阅了CellBeginEdit和CellEndEdit事件,并将结果添加到一个字典中,如果有任何更改,最终的结果将是您可以简单地迭代该包含单元格作为其键和(在我的情况下是对象,在您的情况下是组合框值之前的)先前值的字典。
    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);
            }
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接