如何在编辑模式下比较datagridview中单元格的值?换句话说,我想提出一个" YES NO"对话框指向最终用户并显示旧值和他编辑的新值。
答案 0 :(得分:0)
在表单加载中,我创建了一些列和行,
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;
}
现在,CellBeginEdit
和CellEndEdit
可以解决问题。
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;
}
}
}
希望有所帮助,
答案 1 :(得分:0)
CellBeginEdit和CellEndEdit事件会在CellValueChanged事件之前或之后触发吗?现在,我正在捕获CellValueChanged事件中的值并更新数据库。