检查DataGridView中的值是否修改

We can register the events "CellBeginEdit", "CellValidating" and "CellEndEdit" at the same time to get the two values before and after the modification and compare them.

    string begin = "";
    string end = "";

    private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
    {
        if (dataGridView1.CurrentCell.Value == null)
        {
            begin = "";
        }
        else
        {
            begin = dataGridView1.CurrentCell.Value.ToString();
        }
    }

    private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        end = e.FormattedValue.ToString();
    }

    private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        if (begin != end)
        {
            MessageBox.Show("Value Changed!");
        }
    }

转载于:https://www.cnblogs.com/jizhiqiliao/p/10490552.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以通过以下步骤将 DataGridView 修改过的更新到数据表: 1. 添加一个按钮或菜单项来触发保存操作。 2. 在保存操作的事件处理程序,遍历 DataGridView 的每一行。 3. 对于每一行,检查它的状态。如果状态为“修改”,则将新的更新到数据表。 以下是一个简单的示例代码: ``` private void btnSave_Click(object sender, EventArgs e) { // 遍历 DataGridView 的每一行 foreach (DataGridViewRow row in dataGridView1.Rows) { // 检查行的状态是否为“修改” if (row.Cells[0].Value != null && row.Cells[0].Value.ToString() == "修改") { // 更新数据表对应的记录 int id = int.Parse(row.Cells["id"].Value.ToString()); string name = row.Cells["name"].Value.ToString(); int age = int.Parse(row.Cells["age"].Value.ToString()); string sql = "UPDATE mytable SET name = @name, age = @age WHERE id = @id"; using (SqlConnection conn = new SqlConnection("连接字符串")) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddWithValue("@name", name); cmd.Parameters.AddWithValue("@age", age); cmd.Parameters.AddWithValue("@id", id); conn.Open(); cmd.ExecuteNonQuery(); } } } } ``` 在这个示例,我们假设 DataGridView 包含三列:id、name 和 age。我们还假设数据表的名称为 mytable。当用户点击“保存”按钮时,我们遍历 DataGridView 的每一行,并检查它的状态。如果状态为“修改”,则将新的 name 和 age 更新到数据表

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值