I need to detect the changes that were made to the form, either in TextBox
, Datagridview
or other controls.
Here I leave a small example as a test code (GoogleDrive link)
IdentificarCambios.zip
This works perfectly for me , but I think there should be a more optimal and practical method. I know that it
Dataset
contains a method calledHasChanges
but I don't know how to use it to get the result I want.
Here I start the explanation:
Here we see this form as you can see Boton Salvar
it is disabled, because it is the original data initially loaded. If I make a change in any of these cells: Hora Entrada
, Hora Salida
, Cantidad
after the event is fired a call CellEndEdit
is invoked which works as follows:Función
verificar_cambios
Initially when the data is loaded I have two
dataset
of which I copy the original dataset to the second dataset so that they contain the same data, then in the functionVerificar_cambios
I perform the validation of whether the value found in itdataset original
is the same as that found in theotro dataset
if is the same thebotón Salvar
is not enabled, otherwise thebotón Salvar
is enabled.
As you can see in the second image I have changed the value of the celda
to 5
function 10
was invoked and enabled the botón salvar
. But if usuario
he puts its value back into 5
the function again deshabilita
the botón salvar
. I don't know how to achieve that with HasChanges
.
EDITED
Code Snippet:
When you load the data:
dataset_cambios = dataset_datos.Copy();
Check Changes function:
private void verificar_cambios()
{
string cantidad = string.Empty cantidad_cambios = string.Empty;
for (int fila = 0; fila < dataset_datos.Tables[0].Rows.Count; fila++)
{
if (dataset_datos.Tables[0].Rows[fila]["cantidad"].ToString() == string.Empty)
cantidad = string.Empty;
else
cantidad = dataset_datos.Tables[0].Rows[fila]["cantidad"].ToString().Trim();
if (dataset_cambios.Tables[0].Rows[fila]["cantidad"].ToString() == string.Empty)
cantidad_cambios = string.Empty;
else
cantidad_cambios = dataset_cambios.Tables[0].Rows[fila]["cantidad"].ToString().Trim();
//Verificando si la variable del dataset original es diferente a la del dataset guardado inicialmente.
if (cantidad.Equals(cantidad_cambios))
{
//No hay cambios
btn_salvar.Enabled = false;
}
else
{
//Si hay cambios
btn_salvar.Enabled = true;
break;
}
}
}
So how do I optimize this method, or create a more efficient one?
Note: I have not placed all the code of the project so as not to enlarge the publication so much.
Visual Studio 2010 and the .NET Framework 4
It would be much easier if you work with collections of objects and Linq, even better with entity framework and changetracker, but for the example you have passed this is a solution:
Add AcceptChanges in the generate_data method (changes will be obtained from now on)
To get the changes in the check_changes method
This way we recover the current values and the original ones