Update SQL from DataGridView - IndexOutOfRangeException "Cannot find table (0)' error

Moordoom

Member
Joined
Nov 12, 2013
Messages
23
Programming Experience
1-3
Update SQL from DataGridView - IndexOutOfRangeException "Cannot find table (0)' error

I am trying to save changes (UPDATE) from a DataGridView to the SQL Table it was pulled from.
It pulls the data fine, I can make my adjustments, but when I click my button to update I get a
"IndexOutOfRangeException "Cannot find table (0)' error" error.
I am just wanting to update the changes I made to the data I pulled.
Any help is greatly appreciated.
VB.NET:
 Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click        
        Dim daSWC2 As New SqlDataAdapter        
        Dim SQLcmdBuilder2 As New SqlCommandBuilder(daSWC2)
        Dim ds2 as New DataSet
        DataGridView1.Datasource = ds2.Tables(0) 'ERROR is HERE
        daSWC2.Update(DataGridView1.DataSource)
        MessageBox.Show("Items have been Updated")
        DataGridView1.DataSource = Nothing
        DataGridView1.Rows.Clear()
        DataGridView1.Columns.Clear()
 End Sub
Data is pulled in a button click sub before this one with the SQLConnection declared in Private in the Public Class form.
 
You just created 'ds' so it has no tables, so there's no table at index zero. You shouldn't be creating all those objects in that event handler. You should already have a DataTable, a data adapter and a command builder because you should have created them when you retrieved the data in the first place. If you really must, you can create a new data adapter and command builder, although there's no good reason to, but what you cannot create is a new DataSet/DataTable because it won't contain any data anyway. Check out the following thread for an example of the sort of thing you should be doing:

Retrieving and Saving Data in Databases
 
Back
Top