Getting ArgumentOutOfRangeException when populating data grid view with data

  • Thread starter Thread starter SagaV9
  • Start date Start date
S

SagaV9

Guest
Hi all, I am using VS 2015 C# with a data grid view in a Win Forms app. The data grid view loads correctly and is totally functional.

The data grid view SelectionMode is set to Full Row Select and MultiSelect is set to false

I need to be able to navigate the grid using the keyboard (up and down arrow keys), and get the product id as the row is selected.

To catch when the user presses the up/down keys, I added a SelectionChanged event. There I have the following code:


ProdId = dbgData.SelectedCells[0].Value.ToString();

MessageBox.Show("Here in Selection changed, row " + dbgData.CurrentCell.RowIndex + "\n\n" +
"Row count: " + dbgData.Rows.Count + "\n\n" +
"Id: " + dbgData.SelectedCells[0].Value.ToString());

When I run the program and load the grid I get the following message:

1428261
1428267.png

That looks ok, id 500190 corresponds to the first item in the grid: row 0. The event seems to have been triggered when the grid starts to load because I know I have more than 1 record to load. However, when I click the Ok button I get this exception:

1428262.png

This tells me that the event was triggered again, causing the exception on the second go around.

I added a try/catch block:

try
{
ProdId = dbgData.SelectedCells[0].Value.ToString();

MessageBox.Show("Here in Selection changed, row " + dbgData.CurrentCell.RowIndex + "\n\n" +
"Row count: " + dbgData.Rows.Count + "\n\n" +
"Id: " + dbgData.SelectedCells[0].Value.ToString());
}
catch (ArgumentOutOfRangeException OoREx)
{
ProdId = "";
MessageBox.Show(OoREx.Message + "\n\n Row: " + dbgData.CurrentCell.RowIndex);
}

When I run the app I get the first message as shown above. When I click the OK button, I get the exception, as shown above. When I click the Ok button, I get the first message, indicating that it successfully got the id number. When I click the Ok button, I again get the exception. This indicates that the event is triggered four times while the grid is loaded. It succeeds twice and it fails twice.

The try/catch block gets me around this behavior and the exception. After the grid is loaded I can successfully use the arrow keys to navigate the grid; however, I am not happy with the solution, that seems more like a kludge. Any advice or feedback on a better solution is welcomed. Thank you, Saga








You can't take the sky from me

Continue reading...
 
Back
Top