blah blah blah is here! blah blah » Close

up0down
link

Hi,

I need to copy the selected cell as text in datagridview, I used the following code and it works just fine.

private void main_ListDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
Clipboard.SetText(main_ListDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
}


However, when I click any header to sort the rows, it gives an error. It says

"ArgumentOutOfRangeException was unhandled".

Any idea to solve this?

last answered one year ago

1 answers

link

the get_Item method of the Rows collection will throw that exception if the specified rowIndex is less than zero. Add a check to ensure that the handler will not try to access the Rows collection if the rowIndex is invalid. Also, I would add a check to ensure that the Value property of the selected cell is not null.

private void main_ListDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
if(e.RowIndex >= 0 && main_ListDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
Clipboard.SetText(main_ListDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
}

ademmeda
108

Thank you very much, this solved the problem.

Feedback