【问题标题】:Datagridview check for changes and insert recordsDatagridview 检查更改并插入记录
【发布时间】:2015-06-22 01:31:48
【问题描述】:

我有一个从包含可编辑列的 SQL Server 数据库加载的 datagridview。我想检查用户是否更改了 datagridview 中的数据,然后我可以将数据保存回数据库,如果用户没有更改任何内容,则不会将数据保存到数据库中。我不想更新原始记录上的数据,在 datagridview 更改后它应该将数据插入回数据库。主模板和用户模板之类的东西。

【问题讨论】:

    标签: c# asp.net sql-server datagridview


    【解决方案1】:

    DataGridViewCell 不跟踪更改。如果您需要知道仅一个单元格的值已更改,请使用 CellValueChanged 事件并在那里执行您的操作。如果您需要知道哪些单元格已被修改,以便枚举它们并执行必要的操作,请尝试以下操作:

    HashSet<DataGridViewCell> changedCells = new HashSet<DataGridViewCell>();
    private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        DataGridView dgv = sender as DataGridView;
        if (!changedCells.Contains(dgv[e.ColumnIndex, e.RowIndex]))
        {
            changedCells.Add(dgv[e.ColumnIndex, e.RowIndex]);
        }
    }
    

    别忘了挂钩 DataGridView 的 CellValueChanged 事件。当您需要更改单元格的列表时,请执行以下操作:

    foreach (DataGridViewCell cell in changedCells)
      {
         // Your work here
      }
    

    这仅适用于 UI 级别。如果您的数据也被代码更改,您将需要不同的方法。

    See here for complete reference

    查看[Nikola Markovinović][2] 答案

    【讨论】:

    • 感谢您的回复,但实际上我正在寻找的是在插入记录之前检查 gridview 中的任何更改。我的 gridview 中有模板字段可供编辑,但编辑后我怎么知道用户已更改任何内容。
    【解决方案2】:

    我认为你可以使用 asp.net 网格的OnRowUpdating="GridViewUpdateEventHandler"

    【讨论】:

    • DataGridView 是 WinForms 控件,而不是 ASP.NET 网格控件。
    猜你喜欢
    • 2011-12-11
    • 2015-10-04
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多