I have a DataGridView
populated from a database.
I am trying to get the contents of the row that is selected on the RowEnter
event. I have set the grid's selection mode to FullRowSelect
I have tried the following:
int orderId = (int)dgUnprocessedCards.Rows[dgUnprocessedCards.SelectedCells[0].RowIndex].Cells[0].Value;
this keep throwing the error
Index was out of range. Must be non-negative and less than the size of the collection.
Any help is appreciated.
I've just tried this in a sample datagridview app and it works just fine so there must be something going on which you haven't told us about.
First thing to do is break your one big statement up into discrete smaller statements so you can see exactly where the failure is.
You can rewrite the code above to something like this for debugging purposes:
var cellindex = dgUnprocessedCards.SelectedCells[0].RowIndex;
var cellcollection = dgUnprocessedCards.Rows[cellindex].Cells[0];
int orderId = (int)dgUnprocessedCards.Value;
Also, you should be able to do the following to achieve what you want:
int orderId = (int)dataGridView1.SelectedRows[0].Cells[0].Value;
That uses the SelectedRows collection which is a little bit more concise and I'd say the more usual way of accessing selected items from the datagridview.
Finally, you probably want to do checking around your cast of the value, since the Value might not necessarily be an int. Something like:
int orderid;
if (!int.TryParse(cellcollection.Value.ToString(), out orderid))
{
// Some logic to deal with the fact that Value was not an int
}
When is the SelectionChanged event raised?
Now - as you mention, your selection changed event fires while loading data into the grid. This doesn't seem to cause a problem in my test version but could be part of your issue.
Why this happens should not be related to the type of data source you are using, but to when you attach the selection changed eventhandler. This is because databinding causes a selection changed event to be raised.
If you add an eventhandler for the DataBindingComplete event and attach your SelectionChanged or RowEnter eventhandlers there, you should not see the handler invoked during databinding.
void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
this.dataGridView1.RowEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_RowEnter);
this.dataGridView1.SelectionChanged += new System.EventHandler(this.dataGridView1_SelectionChanged);
}
Note that you will need to delete the designer generated event attachment and reference the designer generated methods for this to work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With