I have a DataGridView. I have to compare the old and the new cell values and perform further action.
I tried comparing with Cell Leave
, CellValidating
events by using the following code,
private void TestGrid_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
int currentCell = TestGrid.CurrentCell.ColumnIndex;
var oldCellValue = TestGrid[e.ColumnIndex, e.RowIndex].Value;
var newValue = e.FormattedValue;
}
It returns my Old value and new value both as eg: 1000 when I try clicking on the different cell.
Please, let me know if there is any other event through which I can achieve the desired behaviour. Also If I have to compare the old and new cells row or column indexes then how to proceed?
private void TestGrid_CellLeave(object sender, DataGridViewCellEventArgs e)
{
int currentCell = TestGrid.CurrentCell.ColumnIndex;
int oldCell = e.ColumnIndex;
}
Both them returns same index.
Try with the EditedFormattedValue
property of the DataGridView
. Tested this one and I see the different values:
private void TestGrid_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
int currentCell = TestGrid.CurrentCell.ColumnIndex;
var oldValue = TestGrid[e.ColumnIndex, e.RowIndex].Value;
var newValue = TestGrid[e.ColumnIndex, e.RowIndex].EditedFormattedValue;
/* Perform some logic here*/
}
Try converting the cell values into strings and do something similar like this (code example comes from MSDN). Hope this helps.
// Iterate through the SelectedCells collection and sum up the values.
for (counter = 0;
counter < (DataGridView1.SelectedCells.Count); counter++)
{
if (DataGridView1.SelectedCells[counter].FormattedValueType ==
Type.GetType("System.String"))
{
string value = null;
// If the cell contains a value that has not been commited,
// use the modified value.
if (DataGridView1.IsCurrentCellDirty == true)
{
value = DataGridView1.SelectedCells[counter]
.EditedFormattedValue.ToString();
}
else
{
value = DataGridView1.SelectedCells[counter]
.FormattedValue.ToString();
}
if (value != null)
{
// Ignore cells in the Description column.
if (DataGridView1.SelectedCells[counter].ColumnIndex !=
DataGridView1.Columns["Description"].Index)
{
if (value.Length != 0)
{
SelectedCellTotal += int.Parse(value);
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.