Dear Aaron!
You can save the DataTable back 2 your SQL Server database in 2 ways:
1 - You can loop through each row in the DataTable, build a SQL statement dynamically and excute it against the database, OR
2- You can use a SqlDataAdapter object, configure its InsertCommand and call its update method passing it the DataTable object.
Assume the following:-
1 - You have an open conn named 'nwind' to the Northwind SQL Server db
2 - Your DataTable's name is custsTable and is populated with data
3 - The custsTable represents Customers table & contains these fields
(a) CustomerID
(b) CompanyName
(c) ContactName
4 - You have a DataSet named nwindDataSet and you have added your table, custsTable, to this DataSet
Now here goes method 1:-
------------------------------------------------
Dim custsInsCmd As SqlClient.SqlCommand
Dim custRow As DataRow
Dim sql As String
custsInsCmd = nwind.CreateCommand()
For Each custRow In custsTable.Rows
sql = "INSERT INTO Customers (CustomerID, " & _
"CompanyName, ContactName) VALUES (" & _
"'" & custRow("CustomerID") & "', " & _
"'" & custRow("CompanyName") & "', " & _
"'" & custRow("ContactName") & "')"
custsInsCmd.CommandText = sql
custsInsCmd.ExecuteNonQuery()
Next
------------------------------------------------
Now here goes method 2:-
------------------------------------------------
Dim custsAdapter As New SqlClient.SqlDataAdapter
Dim custsInsCmd As SqlClient.SqlCommand()
' Create Insert cmd and set its Command Text
custsInsCmd = nwind.CreateCommand()
custsInsCmd.CommandText = "INSERT INTO Customers (CustomerID, " & _
"CompanyName, ContactName) VALUES (@CustomerID, @CompanyName, " & _
"@ContactName)"
custsInsCmd.CommandType = CommandType.Text
' Add parameters to the Insert command
custsInsCmd.Parameters.Add("@CustomerID", SqlDbType.NChar, _
5, "CustomerID")
custsInsCmd.Parameters.Add("@CompanyName", SqlDbType.NVarChar, _
40, "CompanyName")
custsInsCmd.Parameters.Add("@ContactName", SqlDbType.NVarChar, _
30, "ContactName")
' Initialize the DataAdapter's Insert Command
custsAdapter.InsertCommand = custsInsCmd
' Send data table rows back to the data source
custsAdapter.Update(custsTable)
------------------------------------------------
I hope this code helps you.
ejan
|