比较旧的和新的值在datagridview单元格在编辑更多

本文关键字:单元格 编辑 datagridview 比较 | 更新日期: 2023-09-27 18:11:23

如何在编辑模式下比较datagridview中的单元格值?换句话说,我希望向最终用户呈现一个"YES NO"对话框,并显示他编辑的旧值和新值。

比较旧的和新的值在datagridview单元格在编辑更多

在表单加载中,我创建了一些列和行,

private void Form1_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("test1");
            dt.Columns.Add("test2");
            dt.Columns.Add("test3");
            string[] row = new string[] { "1", "Product 1", "1000" };
            dt.Rows.Add(row);
            row = new string[] { "2", "Product 2", "2000" };
            dt.Rows.Add(row);
            row = new string[] { "3", "Product 3", "3000" };
            dt.Rows.Add(row);
            row = new string[] { "4", "Product 4", "4000" };
            dt.Rows.Add(row);
            dataGridView1.DataSource = dt;
        }

现在,CellBeginEditCellEndEdit就可以了。

string tempValue = "";
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
    {
        tempValue = dataGridView1.CurrentCell.Value.ToString(); // every edit start took the value and put it to tempValue.
    }
    private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        if (tempValue != dataGridView1.CurrentCell.Value.ToString()) // we need to compare tempValue and currentValue. If we don't, even we don't do any changes it will show dialog result.
        {   // take the current value (changed value)
            string currentValue = dataGridView1.CurrentCell.Value.ToString(); 
            DialogResult dialogResult = MessageBox.Show("old value:" + tempValue + " new value:" + currentValue, "Confirm Change", MessageBoxButtons.YesNo); //show dialog result
            if (dialogResult == DialogResult.Yes) // if yes do something
            {
                // yes
            }
            else if (dialogResult == DialogResult.No) // if no cancel changed value set old value which is tempValue.
            {
                dataGridView1.CurrentCell.Value = tempValue;
            }
        }
    }

希望帮助,

CellBeginEdit和CellEndEdit事件会在cellvaluechange事件之前或之后触发吗?现在,我正在捕获CellValueChanged事件中的值并更新数据库。