I have a C# winforms application and I am trying to get a button working that will select the next row in a datagridview after the one curently selected.
The code I
First, set "Multiselect" property of datagridview to false.
int currentRow = dataGridView1.SelectedRows[0].Index;
if (currentRow < dataGridView1.RowCount)
{
dataGridView1.Rows[++currentRow].Selected = true;
}
It will select the next row in the datagridview.
It's here:
dataGridView1.SelectedRows[selectedRowCount]
If you have 3 selected rows then selectedRowCount = 3 and there are three rows with indexes: 0, 1, 2.
You are trying to access #3 which doesn't exist.
dgv_PhotoList.Rows[dgv_PhotoList.CurrentRow.Index+1].Selected = true;
this example to read value cell or column is number 4 of datagridview
int courow = dataGridView1.RowCount-1;
for (int i=0; i < courow; i++)
{
MessageBox.Show(dataGridView1.Rows[i].Cells[4].Value.ToString());
}
try this:
int nRow;
private void Form1_Load(object sender, EventArgs e)
{
nRow = dataGridView1.CurrentCell.RowIndex;
}
private void button1_Click(object sender, EventArgs e)
{
if (nRow < dataGridView1.RowCount )
{
dataGridView1.Rows[nRow].Selected = false;
dataGridView1.Rows[++nRow].Selected = true;
}
}
I prefer this row selection :
First check if no multiselect : number_of_data Then get the select cell (or row) : row_index
private void next_click(object sender, EventArgs e)
{
int number_of_data = dataGridView.SelectedRows.Count;
if (number_of_data > 1) return;
int row_index = dataGridView.SelectedCells[0].RowIndex;
if (row_index < dataGridView.RowCount-1)
{
dataGridView.Rows[row_index++].Selected = false;
dataGridView.Rows[row_index].Selected = true;
}
// Do something
}