I am browsing the DataGridView
records through the actions of the Anterior
and Siguiente
buttons, the current method that works correctly to scroll through each record. But I used this code for combining the same cells in DataGridView in Winforms .
Fictitious data for example:
Then with the method I have it moves in the registers one by one, but I need to move to the next one avoiding the record if it has the same value in the cell, like moving the previous record while it is not equal the value of the cell .
I have the following CurrentCellChanged
:
int indice = 0;
private void myDataGrid_CurrentCellChanged(object sender, EventArgs e)
{
if (myDataGrid.CurrentRow != null)
indice = myDataGrid.CurrentRow.Index;
}
Anterior
button:
private void boton_anterior_Click(object sender, EventArgs e)
{
int anterior = indice - 1;
myDataGrid.CurrentCell = myDataGrid.Rows[anterior].Cells[myDataGrid.CurrentCell.ColumnIndex];
}
Botoon Siguiente
:
private void boton_siguiente_Click(object sender, EventArgs e)
{
int siguiente = indice + 1;
myDataGrid.CurrentCell = myDataGrid.Rows[siguiente].Cells[myDataGrid.CurrentCell.ColumnIndex];
}
To solve the problem of moving to the previous / next record if the value of the cell does not repeat, I tried the following:
bool IsTheSameCellValue(int column, int row)
{
DataGridViewCell cell1 = dataGridView1[column, row];
DataGridViewCell cell2 = dataGridView1[column, row - 1];
if (cell1.Value == null || cell2.Value == null)
{
return false;
}
return cell1.Value.ToString() == cell2.Value.ToString();
}
private void boton_anterior_Click(object sender, EventArgs e)
{
int anterior = indice - 1;
if (IsTheSameCellValue(0, anterior))
{
anterior--;
myDataGrid.CurrentCell = myDataGrid.Rows[anterior].Cells[myDataGrid.CurrentCell.ColumnIndex];
}
else
myDataGrid.CurrentCell = myDataGrid.Rows[anterior].Cells[myDataGrid.CurrentCell.ColumnIndex];
}
private void boton_siguiente_Click(object sender, EventArgs e)
{
int siguiente = indice + 1;
if (IsTheSameCellValue(0, siguiente))
{
siguiente++;
if (siguiente == myDataGrid.Rows.Count)
siguiente--;
myDataGrid.CurrentCell = myDataGrid.Rows[siguiente].Cells[myDataGrid.CurrentCell.ColumnIndex];
}
else
myDataGrid.CurrentCell = myDataGrid.Rows[siguiente].Cells[myDataGrid.CurrentCell.ColumnIndex];
}
How can I solve it?
Environment: Visual Studio 2010 - C # (WindowsForms) & .NET NetFramework 4