Column 'xxxx' does not belong to underlying table '' error - sql-server

please advise; what is wrong in this code ?
giving below error ... Column 'xxxx' does not belong to underlying table ''.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim connStr As String = ConfigurationManager.ConnectionStrings("FBB-DSL-DBConnectionString").ConnectionString
Dim tablex As New DataTable()
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand("sp_columns", conn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#table_name", "tbl_EmpRecords")
' get the adapter object and attach the command object to it
Using ad As New SqlDataAdapter(cmd)
' fire Fill method to fetch the data and fill into DataTable
ad.Fill(tablex)
End Using
End Using
End Using
'Creating DataView
Dim view As New DataView(tablex)
Dim dt As DataTable = view.ToTable(False, "COLUMN_NAME" )
CheckBoxList1.DataSource = dt
CheckBoxList1.DataBind()
End If
End Sub

The system defined stored procedure sp_columns produces a datatable where each row contains the schema details of the columns in the tbl_EmpRecords.
This means that the columns present in this tablex are the following:
TABLE_QUALIFIER,
TABLE_OWNER,
TABLE_NAME,
COLUMN_NAME,
DATA_TYPE,
TYPE_NAME,
PRECISION,
LENGTH,
SCALE,
RADIX,
NULLABLE,
SQL_DATA_TYPE,
SQL_DATETIME_SUB,
CHAR_OCTET_LENGTH,
ORDINAL_POSITION,
IS_NULLABLE,
SS_DATA_TYPE
See the MSDN docs about sp_columns for the meaning of each column.
So, there is no column named XXXXXX and this is exactly what the error tells you. If you really want to create a new datatable with only one column then your XXXXX field should be one of the above names.
' This will return a new table with only one column named COLUMN_NAME'
' The table will contain all the column names of the table tbl_EmpRecords'
Dim dt As DataTable = view.ToTable(False, "COLUMN_NAME")
Instead, if you are trying to sort the tbl_EmpRecords using someone of the fields defined in that table (IE, empName, HireDate etc....) then you have to use a different approach for your query.
....
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand("select * from tbl_EmpRecords", conn)
Using ad As New SqlDataAdapter(cmd)
ad.Fill(tablex)
End Using
End Using
End Using
....
then you can proceed with the DataView code.
However, it is always better to query the database to retrieve only the data you are interested in.
So, if you need only the field XXXXX then just use the query
select XXXXX from tbl_EmpRecords
and probably you can ask the database to sort that record for you with
select XXXXX from tbl_EmpRecords ORDER BY XXXXX
removing all the DataView code.

Related

Inserting data into database with autonumber in VB.net

I'm trying to insert data into a database with an autonumber in MS Access as primary key. I get an error saying "Number of query values and destination fields are not the same. The data types in MS Access are Autonumber (I didn't include it in the INSERT statement), String (#OrderNo), String (#Product), Number (#Qty), and Date (#TDate). Here's the image:
Here's my code:
For Each row As DataGridViewRow In DataGridView1.Rows
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Daily Inventory.accdb;"
Using conn As New OleDbConnection(connString)
Using cmd As New OleDbCommand("Insert into Table1 Values(#OrderNo, #Product, #Qty, #TDate)", conn)
cmd.Parameters.AddWithValue("#OrderNo", TxtOrder.Text.ToString)
cmd.Parameters.AddWithValue("#Product", row.Cells("Product").Value)
cmd.Parameters.AddWithValue("#Qty", row.Cells("Qty").Value)
cmd.Parameters.AddWithValue("#TDate", Date.Now.ToString("MM/dd/yyyy"))
If conn.State = ConnectionState.Open Then
conn.Close()
End If
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Using
End Using
Next
You need to change your sql to "Insert into Table1 (OrderNo,Product,Qty,TDate) Values(#OrderNo, #Product, #Qty, #TDate)".
The following code works for me.
DataGridView1.AllowUserToAddRows = False
For Each row As DataGridViewRow In DataGridView1.Rows
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=...;"
Using conn As New OleDbConnection(connString)
Using cmd As New OleDbCommand("Insert into Table1 (OrderNo,Product,Qty,TDate) Values(#OrderNo, #Product, #Qty, #TDate)", conn)
cmd.Parameters.AddWithValue("#OrderNo", TxtOrder.Text.ToString)
cmd.Parameters.AddWithValue("#Product", row.Cells("Product").Value)
cmd.Parameters.AddWithValue("#Qty", row.Cells("Qty").Value)
cmd.Parameters.AddWithValue("#TDate", Date.Now.ToString("MM/dd/yyyy"))
If conn.State = ConnectionState.Open Then
conn.Close()
End If
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Using
End Using
Next
Well, I think we dealing with a bit of a chicken and a egg problem here?
I mean, how did the grid get created?
How and where did you setup the columns in the grid?
lets drop a data grid view into a form. Drop in a button.
We have this code to load up the grid:
Private Sub HotelGridEdit_Load(sender As Object, e As EventArgs) Handles Me.Load
LoadGrid()
End Sub
Sub LoadGrid()
Using conn As New OleDbConnection(My.Settings.AccessDB)
Dim strSQL As String =
"SELECT ID, FirstName, LastName, City, HotelName, Description, Active FROM tblHotelsA
ORDER BY HotelName"
Using cmdSQL As New OleDbCommand(strSQL, conn)
conn.Open()
Dim rstData As New DataTable
rstData.Load(cmdSQL.ExecuteReader)
DataGridView1.DataSource = rstData
End Using
End Using
End Sub
So, now we have this:
Now, in a above, I can cursor around - make any edits I want.
I can also type in on the bottom blank row to add new rows.
I can click on the left side recordselector, and hit delete key.
Now, to save my edits, save my addtitions, and save my deletes?
I have the one button at the top, and this code works to do all updates, all addtitions, and all deletes.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' save all edits, and new rows, and deletes
Using conn As New OleDbConnection(My.Settings.AccessDB)
Dim strSQL As String =
"SELECT ID, FirstName, LastName, City, HotelName, Description, Active FROM tblHotelsA"
Using cmdSQL As New OleDbCommand(strSQL, conn)
conn.Open()
Dim da As New OleDbDataAdapter(cmdSQL)
Dim daC As New OleDbCommandBuilder(da)
da.Update(DataGridView1.DataSource)
End Using
End Using
End Sub
So, not a lot of code.
In fact, often using a data table is a lot less work, since you don't have to mess with all those parameters anyway - even if your data grid was somehow not feed from the database. But, if you feeding the "grid" from the database, then really, you can just add rows - and then write some code to send the changes back to the database with the above code. And if you want to start out with a blank grid - not show previous rows, then just add to your sql like this:
SELECT * from tblHotels WHERE ID = 0 Order by Hotelname
Use above to create a data table without any rows but STILL bind that to the grid, and thus once again, to add, or delete rows, you just edit and add them, and again the SAME code I had above will work to save edits, deletes and additions.

How to display all elements in a column using cmd.ExecuteReader from mdf data file in Visual Basic

Here's my .mdf database file that has 5 columns
I want to add each of those values from my Id column in a list
Private Sub Read_Click(sender As Object, e As EventArgs) Handles Read.Click
Try
If con.State = ConnectionState.Open Then
con.Close()
End If
con.Open()
cmd = con.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT Id FROM tablekongbago"
cmd.ExecuteNonQuery()
Dim dr As SqlClient.SqlDataReader
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
While dr.Read
element = dr.GetInt32(0).ToString()
End While
Catch ex As Exception
End Try
MessageBox.Show(element)
End Sub
The problem is that I can only retrieve the last row of my Id column and not all of the values from my Id column using
element = dr.GetInt32(0).ToString()
If I try to iterate and turn it into
dr.GetInt32(1).ToString()
it displays nothing.
I want to create a collection of Id's to a List(Of Integer) I know how to create a list and a for loop but I don't know how can I retrieve all of my Id's from my Id column, what kind of code should I use if "dr.GetInt32(0)" is only for the last row of the Id column?, is there a way I can loop starting from the very first top row up to the last row of my Id column? I want something like "list[0] - referring to the first row and list[2] - referring to the last row, so that I can add it my List(Of Integer).
I cringe whenever I see If con.State = ConnectionState.Open Then. Connections should be declared in the method where they are used. You should never have to question the ConnectionState.
You have executed your command twice. A Select in not a NonQuery. NoQuery is Insert, Update and Delete.
Your While loop keeps overwriting the element varaiable on each iteration so you only get the value in the last record.
Never write an empty Catch block. It will just swallow errors and you may get unexpected results with no clue why.
It is a good idea to separate you database code from you user interface code.
Create your connection and command with a Using...End Using block so you know they are properly disposed. Likewise with the reader. I like to do as little as possible with a reader because it requires and open connection and connections should be open for as short a time as possible.
Private ConStr As String = "Your connection string"
Private Sub Read_Click(sender As Object, e As EventArgs) Handles Read.Click
Dim dt As DataTable
Try
dt = GetIds()
Catch ex As Exception
MessageBox.Show(ex.Message)
Return
End Try
Dim ListOfIDs = (From row As DataRow In dt.AsEnumerable
Select CInt(row(0))).ToList
ListBox1.DataSource = ListOfIDs
End Sub
Private Function GetIds() As DataTable
Dim dt As New DataTable
Using con As New SqlConnection(ConStr),
cmd As New SqlCommand("SELECT Id FROM tablekongbago;", con)
con.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
You can simply create a List of Integer and add the ids to your collection during each call to dr.Read()
Dim ids = New List(Of Integer)()
While dr.Read()
ids.Add(dr.GetInt32(0))
End While
You code looks a bit messed up. This should work:
Note that a sql command object is VERY nice.
It has a reader built in - you don't need to define one
It has the command text - you don't need to define one
it has a connection object - again no need to create one (but you look to have one)
And using a dataTable is nice, since you can use for/each, or use the MyTable.Rows(row num) to get a row.
And a datatable is nice, since you don't need a loop to READ the data - use the built in datareader in sqlcommand object.
Using cmdSQL As New SqlCommand("Select Id FROM tblekingbago", con)
cmdSQL.Connection.Open()
Dim MyTable As New DataTable
MyTable.Load(cmdSQL.ExecuteReader)
' table is now loaded with all "ID"
' you can see/use/display/play/have fun with ID like this:
For Each OneRow As DataRow In MyTable.Rows
Debug.Print(OneRow("Id"))
Next
' display the 5th row (it is zero based)
Debug.Print(MyTable.Rows(4).Item("Id"))
End Using

VB.Net forms application database table update

I am attempting to make a small application allowing users to read the content of a table describing the inventory of a warehouse, search depending on 2 rows indicating which warehouse the item resides in and by it's assigned barcode which i already managed to get to work by using a binding source, and a datagrid view, updating the view trough a query taking the barcode and location as strings from two boxes.
The second part i would need for this application to suit my basic objective would be to have a way to add new lines and store them into the original table on the database so users could add the new items independently from the warehouses directly.
So far i have encountered 2 issues: i need a primary key that would represent a sequential ID but i do not know how to produce a sequentially incrementing ID, i manage to get the first addition ID by using a top 1 order by desc query combination but the data does not get updated after adding the new line, producing an error since it tries to add another line with the same value for the primary key.
The second issue i am encountering is: the gridview gets altered accordingly to the data i input in the textboxes i set up to gather the various values for the table but the table on the database itself is not showing any change, keeping only the test data i inputted at it's creation.
Public Class AddItems
Private Sub AddItems_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'MagazzinoDataSet.LastUsedID' table. You can move, or remove it, as needed.
Me.LastUsedIDTableAdapter.LastUsedID(Me.MagazzinoDataSet.LastUsedID)
'TODO: This line of code loads data into the 'MagazzinoDataSet.Stock' table. You can move, or remove it, as needed.
Me.StockTableAdapter.Fill(Me.MagazzinoDataSet.Stock)
'TODO: This line of code loads data into the 'MagazzinoDataSet.AddWarehouseList' table. You can move, or remove it, as needed.
Me.AddWarehouseListTableAdapter.AddWarehouseList(Me.MagazzinoDataSet.AddWarehouseList)
'TODO: This line of code loads data into the 'MagazzinoDataSet.WarehouseList' table. You can move, or remove it, as needed.
Me.WarehouseListTableAdapter.Fill(Me.MagazzinoDataSet.WarehouseList)
'TODO: This line of code loads data into the 'MagazzinoDataSet.Stock' table. You can move, or remove it, as needed.
Me.StockTableAdapter.Fill(Me.MagazzinoDataSet.Stock)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim R As DataRow = MagazzinoDataSet.Tables("Stock").NewRow()
R("Supplier") = Supplier.Text
R("Producer_code") = ProducerCode.Text
R("Barcode") = Barcode.Text
R("Comp_name") = ComponentName.Text
R("Warehouse") = Warehouse.Text
R("Internal_Code") = InternalCode.Text
R("Description_IT") = ITDescr.Text
R("Description_EN") = ENDescr.Text
'R("ID") = NextID.SelectedValue <- this would be an hidden uneditable multibox containing the product of the query finding the next value to be inserted in the table (basically last ID + 1, nothing fancy)"ID" would be the primary key of this table
R("Quantity") = "0"
MagazzinoDataSet.Tables("Stock").Rows.Add(R)
DataGridView1.DataSource = MagazzinoDataSet.Stock
End Sub
End Class
To sum it up:
How would i go about updating the database table to include the new line?
Is there a smart way to find the last value, incrementing it by 1 to have the next value and updating it when inserting a new line, so as to not end up with 2 lines with the same value for primary key, generating an error?
To set an incremental ID in the Db, assuming you have access to SQL Server Management Studio, in Design of the table, for the ID column, in Column Properties, scroll down to Identity Specification and set (is Identity) to Yes.
To add a new row, I use this code:
Using NotesDS As New DataSet
Using NotesDA As New SqlDataAdapter With {.SelectCommand = New SqlCommand With {.Connection = SQLDBConnection, .CommandText = "SELECT * FROM Notes WHERE ID = " & ID}}
NotesDA.Fill(NotesDS, "Notes")
Using NotesDV As New DataView(NotesDS.Tables("Notes"))
Using NoteBuilder As New SqlCommandBuilder(NotesDA) With {.QuotePrefix = "[", .QuoteSuffix = "]"}
If NotesDV.Count = 0 Then
Dim NoteDRV As DataRowView = NotesDV.AddNew
NoteDRV.Item("UserName") = UserName
NoteDRV.Item("Note") = Note
NoteDRV.Item("NoteDate") = NoteDate
NoteDRV.Item("CompanyCode") = CompanyCode
NoteDRV.EndEdit()
NotesDA.UpdateCommand = NoteBuilder.GetUpdateCommand
NotesDA.Update(NotesDS, "Notes")
End If
End Using
End Using
End Using
End Using
Obviously, amend to make appropriate for your table and column names.
If you need to retrieve the ID for display, you can add a handler to the Update like:
Public Sub GenericOnRowUpdated(sender As Object, e As System.Data.SqlClient.SqlRowUpdatedEventArgs)
Dim newID As Integer = 0
Dim idCMD As SqlClient.SqlCommand = New SqlClient.SqlCommand("SELECT ##IDENTITY", SQLDBConnection)
If e.StatementType = StatementType.Insert Then
newID = CInt(idCMD.ExecuteScalar())
e.Row("ID") = newID
End If
End Sub
and use like:
AddHandler NotesDA.RowUpdated, New SqlRowUpdatedEventHandler(AddressOf GenericOnRowUpdated)
NotesDA.Update(NotesDS, "Notes")
NewID = NoteDRV.Item("ID")
EDIT
First Example amended and explained below:
'Declare you connection to the SQL dB. Connection String looks like "Data Source=192.168.71.10\dBName; Initial Catalog=dBName; User ID=USER; Password='PASSWORD!';MultipleActiveResultSets=true" - You may well already have an open connection, and can use that instead. Not sure what your
StockBindingSource is...
Dim oConn As New SqlConnection("CONNECTION STRING")
'Open the connection
oConn.Open()
'Declare Your DataAdapter and initialise using your connection
Dim DA As New SqlDataAdapter With {.SelectCommand = New SqlCommand With {.Connection = oConn, .CommandText = "SELECT * FROM Stock WHERE ID=0"}}
'Declare you DataSet
Dim DS As New DataSet
'Fill Your DataSet with the Stock table from your DataAdapter
DA.Fill(DS, "Stock")
'Declare a DataView for easy use (really the same as using DS.Tables("Stock").DefaultView)
Dim DV As New DataView(DS.Tables("Stock"))
'Declare a CommandBuilder and initialise with your DataAdapter. This will now watch for changes made to your data and build the appropriate SQL UPDATE/INSERT/DELETE command. the "[" and "]" are in case any column names use reserved words
Dim Builder As New SqlCommandBuilder(DA) With {.QuotePrefix = "[", .QuoteSuffix = "]"}
'Decalre a DataRowView for data population, based on your DataView table structure
Dim R As DataRowView = DV.AddNew()
'Populate the fileds with your Form data
R("Supplier") = Supplier.Text
R("Producer_code") = ProducerCode.Text
R("Barcode") = Barcode.Text
R("Comp_name") = ComponentName.Text
R("Warehouse") = Warehouse.Text
R("Internal_Code") = InternalCode.Text
R("Description_IT") = ITDescr.Text
R("Description_EN") = ENDescr.Text
R("Quantity") = "0"
'Notify that the edit has finished
R.EndEdit()
'Get the SQL command from the CommandBuilder
DA.UpdateCommand = Builder.GetUpdateCommand()
'Execute the update (in this case it will be an INSERT)
DA.Update(DS, "Stock")

Adding Combobox items from SQL Server using single (and varying) column

First question here, and forewarning I am very new to programming in general, just trying to figure the basics out.
Basically what I am trying to do is select all items in a specified list from my SQL server, add them to an array and then fill a combobox with that array.
The SQL server structure is as follows:
Just a representation
The user will select which product they are building when they log in, and then I would like a combobox to be filled with all of the parts that pertain to that item.
The current code sample
Public Class frmProduct
Private Sub frmProduct_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim mycon As SqlConnection = New SqlConnection('connection string')
mycon.Open()
Using mycon
Dim prodlist As String = frmMain.cmbProduct.SelectedItem
Dim cmds As String = "SELECT DISTINCT(Product) FROM [Products] where Product = #prodlist"
Dim cmde As New SqlCommand(sqlt, mycon)
cmde.Parameters.AddWithValue("#Product", prodlist)
Dim dr As SqlDataReader = scmd.ExecuteReader
If dr.HasRows() Then
cmbFailure.Items.Add(dr.GetString(0))
End If
scmd.ExecuteNonQuery()
End Using
End Sub
End Class
The user selects the Product on the login form, and the selected product is carried over to the parts list form.
The error I am currently recieving which is likely the first of many is "Invalid Column Name Product". I thought that the issue might be that the selected product is not carrying over, but I added a label which I am changing the text to be equal to "prodlist" and it accurately changes the label text.
Again I am fresh meat at all of this, so I apologize for any obvious blunders. Thank you for your help!
In the image you attached the "Product1, Product2, Product3" are fixed columns?
If are, you have to use these columns in your select statement. This is a bad design but will work.
I assume that's a study exercise, so later, can you enhance your project adding 2 tables, one for products and other for store parts of products.
For information about the code.
Private Sub frmProduct_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim mycon As SqlConnection = New SqlConnection('connection string')
Dim cmds As String = "SELECT DISTINCT(Product) FROM [Products] where Product = #prodlist"
Try
' Most of the DB will having a connection fail, so programmer must set a try catch for it '
mycon.Open()
Using mycon
Dim prodlist As String = [Form].[ComBoBox].SelectedItem
Dim cmde As New SqlCommand(sqlt, mycon)
cmde.Parameters.AddWithValue("#Product", prodlist)
Dim dr As SqlDataReader = scmd.ExecuteReader
If dr.HasRows() Then
cmbFailure.Items.Add(dr.GetString(0))
End If
scmd.ExecuteNonQuery()
' For more save for this sql will execute successfully, some of programmer will use Transaction with commit '
' Microsoft Link: https://msdn.microsoft.com/en-us/library/5ha4240h(v=vs.110).aspx '
End Using
' mycon.Close() '
Catch ex As Exception
MessageBox.Show(ex.Message) ' Exception Message '
' [Optional]Release object '
' mycon.Close() '
End Try
End Sub
And for your items with it may crash the result, due to scmd was not same as cmde.
Would you please explain [scmd] is stand for?

SQLCommandBuilder - UPDATE from DataTable only "Appends" Database Table

I am trying to UPDATE database table rows using SQLCommandBuilder with datatable rows using the following test code. One table with a primary key column and one datatable to keep it simple.
Using the following code, the dbo.Dogs2 table is "appended" with the datatable rows - therefore doubling the number of rows rather than just updating the changed row(s)
If I add the code table.AcceptChanges() just before the Dim builder As New SqlCommandBuilder(adapter), the database table dbo.Dogs2 remains unchanged.
If I add the code table.AcceptChanges() just before the adapter.Update(table), the database table dbo.Dogs2 remains unchanged.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' dbo.Dogs2 database table columns are exactly like datatable columns with exception of dog names
' only UPDATING the "Name" field (no Inserts or deletes)
' orginal dog names "Name" in Dogs2.dbo are Sharpy, Bully, Shep, Charlie, and Yorky
' new dog names "Name" in Dogs2.dbo are June, Tucker, Maggie, Charles, and Candy
' Dex_Row_Id is the primary key with Identity Increment set to 1
' Create a DataTable with five columns.
'
Dim table As New DataTable()
table.Columns.Add("Weight", GetType(Integer))
table.Columns.Add("Name", GetType(String))
table.Columns.Add("Breed", GetType(String))
table.Columns.Add("Size", GetType(Char))
table.Columns.Add("Date", GetType(DateTime))
table.Columns.Add("Dex_Row_Id", GetType(Integer))
'
' Add data to the DataTable
'
AddDogRow(table, 57, "June", "Shar Pei")
AddDogRow(table, 130, "Tucker", "Bullmastiff")
AddDogRow(table, 92, "Maggie", "Anatolian Shepherd Dog")
AddDogRow(table, 25, "Charles", "Cavalier King Charles Spaniel")
AddDogRow(table, 7, "Candy", "Yorkshire Terrier")
ShowResult(table) 'displays datatable correctly (this is a DevExpress.com Reference/Extension)
'
' Create new SqlConnection, SqlDataAdapter, and builder.
'
Dim cnString As String = "<<<SQLConnectionString>>>"
'
Using cnSQL1 As New SqlConnection
cnSQL1.ConnectionString = cnString
Using adapter = New SqlDataAdapter("SELECT * FROM Dogs2", cnSQL1)
ShowResult(table) 'displays datatable
Dim builder As New SqlCommandBuilder(adapter)
adapter.UpdateCommand = builder.GetUpdateCommand()
builder.RefreshSchema()
Using New SqlCommandBuilder(adapter)
'
' Fill the DataAdapter with the values in the DataTable.
'
adapter.Fill(table)
ShowResult(table) 'displays datatable + original table data
' Open the connection to the SQL database.
'
cnSQL1.Open()
' Update the SQL database table with the values.
'
adapter.Update(table)
' dbo.Dogs2 now has 10 rows (the 5 rows from the dataset + the original 5 rows)
End Using
End Using
End Using
End Sub
You are using incorrectly the adapter. You should first load the rows from the database, then update the retrieved rows and finally call the update.
' REMOVE THE CODE BEFORE THIS '
' Create new SqlConnection, SqlDataAdapter, and builder.'
Dim cnString As String = "<<<SQLConnectionString>>>"
Dim table = New DataTable() ' Leave it emtpy and without schema'
Using cnSQL1 As New SqlConnection
cnSQL1.ConnectionString = cnString
Using adapter = New SqlDataAdapter("SELECT * FROM Dogs2", cnSQL1)
Dim builder As New SqlCommandBuilder(adapter)
adapter.UpdateCommand = builder.GetUpdateCommand()
' no need of this -> builder.RefreshSchema()'
Using New SqlCommandBuilder(adapter)
adapter.Fill(table)
ShowResult(table) 'displays original table data'
' no need of this -> cnSQL1.Open()'
' NOW YOU COULD CHANGE THE ROWS, FOR EXAMPLE'
table.Rows(0)("Weight") = 99
' Update the SQL database table with the values.'
adapter.Update(table)
End Using
End Using
End Using
When you pass an existing table to the Fill method of the Adapter, the existing record are not removed and thus your table is filled with data from the database and from your manual creation of the table (Of course the Adapter build for you the table columns. Moreover, the rows added manually to your table are marked with the DataRowState.Added while the row modified by your code will be marked with the DataRowState.Changed. This state helps the Update command to decide which action to perform on every row present in the table (Of course the rows that are not changed maintain the initial DataRowState.Unchanged
Finally, calling AcceptChanges doesn't mean that the rows will be updated on the database table. Only the DataRowState flag is reset to the DataRowState.Unchanged

Resources