1

I was getting this error while programming, went through some debugging, googling processes however I could not find the problem and I ask for your help!

        MessageBox.Show(dataGridView1.RowCount.ToString());
        MessageBox.Show(dataGridView1.ColumnCount.ToString());
        MessageBox.Show(dataGridView1.SelectedRows[1].Cells[5].Value.ToString()); //This

According to my research, ArgumentOutOfRangeException is thrown when it's out of range.

From above code, rowcount was 11 and columncount was 7.

However my third line code throws the ArgumentOutOfRangeException: Error

But again, when I put 0 instead of 1 for SelectedRows, it works fine. The rest don't work.

I feel like I'm doing everything right. Can someone please help this beginner? Thank you for reading :)

1
  • 1
    How many rows are selected ,probably you have selected only on row with index 0 Commented May 18, 2016 at 9:02

2 Answers 2

3

The reason is because the SelectedRows is different from the Rows. SelectedRows are the rows which you selected, Rows represent all the Rows you have in your dataGridView1.

Therefore, in your case, although your dataGridView1 has 11 rows, if only two are selected, you could not get SelectedRows with index 2 for example.

If you change your code to use Rows instead:

MessageBox.Show(dataGridView1.Rows[1].Cells[5].Value.ToString()); //This

Then you could get the value in the Rows and Cells with the index as high as the RowCount - 1 and ColumnCount - 1 respectively.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer! I was just referencing the wrong value then. I will accept the answer when in 5 minutes when the website allows me. Thank you again :)
0

Well, the index is zero based, which means that if you select ONE row, the actual selected row is at index 0. What you're trying to do in the code above is to reference the "second" row in the selection. If only one row is selected, this will fail.

Index     Line     Data field   
0         1       Some more data
1         2       Bouncy Castle

1 Comment

Thank you for your explanation! I just didnt have proper understanding of what SelectedRows's value is I guess. Appreciate your attention sir :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.