Change Selected Row of a DataGridView with Code in C #?

0

Good evening to the whole community, my problem is that I have a DataGridView containing name of dishes, and two buttons one that will select the row above the row that is currently selected (if there is one more above) and another that selects the row below the row that is currently selected (if there is one below). I explain myself better with the image:

currently the second row is selected (meat with carrot), I want to make click to the first button (ignore the icons, need to change them) select the row above (meat burritos) and the same with the Bottom button, if it stings with the row that is selected, it would go down to select "stew meat".

Currently this is the code for the first button:

int cantidadElementos = dgvPlatillosPedidos.Rows.Count;

DataGridViewSelectedRowCollection dgvColec = dgvPlatillosPedidos.SelectedRows;
int posActual = dgvPlatillosPedidos.CurrentRow.Index;

if (posActual < (cantidadElementos - 1))
{
    dgvPlatillosPedidos.Rows[posActual - 1].Selected = true;
}

And this code for the second:

int cantidadElementos = dgvPlatillosPedidos.Rows.Count;

DataGridViewSelectedRowCollection dgvColec = dgvPlatillosPedidos.SelectedRows;
int posActual = dgvPlatillosPedidos.CurrentRow.Index;
if (posActual < (cantidadElementos - 1))
{
     dgvPlatillosPedidos.Rows[posActual + 1].Selected = true;
}

But selecting any of them gives me the following error:

I hope you can help me, thank you.

    
asked by U.C 16.04.2018 в 04:35
source

1 answer

1

When you press the upload button you should evaluate when the index becomes zero, because if you continue you would go to a negative value, there you do not need the amount of elements

int posActual = dgvPlatillosPedidos.CurrentRow.Index;

if(posActual == 0)
    return;

dgvPlatillosPedidos.Rows[posActual - 1].Selected = true;

Now when you go down there if you evaluate if you do not reach the end

int cantidadElementos = dgvPlatillosPedidos.Rows.Count;
int posActual = dgvPlatillosPedidos.CurrentRow.Index;

if (posActual == cantidadElementos)
    return;

dgvPlatillosPedidos.Rows[posActual + 1].Selected = true;
    
answered by 16.04.2018 / 05:45
source