DataGridView problems

T

Tony K

When calling my form from within my MDI, I receive this error message.

InvalidOperationException was unhandled
An error occurred creating the form. See Exception.InnerException for
details. The error is: Index was out of range. Must be non-negative and
less than the size of the collection.
Parameter name: index

This error has to do with one line in particular.
Me.Inventory_TransactionsDataGridView.Rows(e.RowIndex).Cells(0).Value =
Today()

If I rem this line out, the form loads. What I want to do is when a cell in
my DataGridView is changed, insert the date into the 1st column of my DGV.
Here are the first several lines of code:

Private Sub Inventory_TransactionsDataGridView_CellValueChanged(ByVal sender
As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs)
Handles Inventory_TransactionsDataGridView.CellValueChanged
If e.ColumnIndex = 1 Then 'when the part# combo box is changed
(2nd column)
Dim cnnProd As New
OleDbConnection(My.Settings.Inventory_management_databaseConnectionString)
'connection used from app settings
Dim cmmProd As OleDbCommand
Dim strSQL As String 'sql statement
Dim description As String
Dim drdProd As OleDbDataReader
Dim prodID As String
Dim unitPrice As Decimal
Me.Inventory_TransactionsDataGridView.Rows(e.RowIndex).Cells(0).Value
= Today()


The last line is the problem line. In the DataGrid I have default cell
style set as DataGridViewCellStyle { Format=d }

What can I do to correct this exception problem that I am receiving?

Thanks,
Tony K
 
C

Cor Ligthert[MVP]

Tony,

Be aware that change events normaly are as well called when controls are
initializing, I would put a check around it to see if the index has a value
(probably it is -1 when initialing however I would look at this if I was you
in the debugger).

Cor
 
T

Tony K

Yes, that was exactly the problem. e.RowIndex was set to -1 because there
were not any rows in the datagridview when the form loaded and because this
was in a CellValueChanged event that one line was executed. I bypassed this
problem by adding an if statement and checking if the number of rows were <=
0 then exit sub. Would that be an ok workaround?

Thanks,
Tony K
 
C

Cor Ligthert[MVP]

Tony,

Very well, you can as well use a switch or add the handler after
initializing, however this one is simple enough,

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top