SqlDataAdapter.Update not updating - database

(I should say that im fairly new to vb.net)
I'm having a problem overwriting the entries in my database. I think the problem is that SqlDataAdapter.Update isn't overwriting the database properly with the new datatable info that i've created.
As I understand it, it should totally replace the the info in the database with the datatable when i tell it to update... no?
Here's the problem in a nutshell:
Basically, I have a database (.mdf file) with a table in it called 'test'. I've used SqlDataAdapter to make a dataset using 'test'. I have another datatable that I've made from parsing in a csv - it's called 'ToLoad'. I now want to clear the 'test' datatable, copy in all entries from the csv datatable, then save this to the database.
I've debugged all this and it all seems to work ok, except when I use SqlDataAdapter.Update I get an error telling me I cant duplicate the primary key. This is because the old entries aren't being cleared from the database entirely, before the new ones are being entered from the datatable.
I've checked that the test datatable is being actually cleared early on in the code... and it is.
I've checked that the new csv entries are being copied to the 'test' datatable... and they are.
Any help you can give on this would be really appreciated
Thanks
Craig
'MAKE A NEW SQL CONNECTION
Dim DBConnection As New SqlConnection
'SET THE CONNECTION STRING.
DBConnection.ConnectionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Project\Members.mdf;Integrated Security=True"
'OPEN THE CONNECTION TO THE DATABASE
DBConnection.Open()
'OPEN AN ADAPTER AND SELECT EVERYTHING FROM THE 'TEST' TABLE
Dim mySqlDataAdapter As New SqlDataAdapter("SELECT * FROM Test", DBConnection)
Dim mySqlCommandBuilder As New SqlCommandBuilder(mySqlDataAdapter)
Dim DBDataset As DataSet = New DataSet
'FILL THE DATASET WITH THE TEST TABLE
mySqlDataAdapter.Fill(DBDataset, "Test")
'CLEAR ALL ENTRIES IN THE DATATABLE (SO I CAN FILL IT FROM SCRATCH)
DBDataset.Tables("test").Clear()
''SET UP A LOOP TO ADD EACH RECORD FROM THE CSV DATATABLE TO THE DATABASE DATATABLE
Dim CSV_row_number As Int16
CSV_row_number = ds.Tables("toload").Rows.Count
Dim i As Int16
i = 0
Do Until i = CSV_row_number - 1
'MAKES TWO NEW DATAROW OBJECTS
Dim DB_row As DataRow
Dim CSV_row As DataRow
'SET THE CSV_ROW OBJECT EQUAL TO ROW(i) OF THE CSV DATATABLE
CSV_row = ds.Tables("toload").Rows(i)
DB_row = DBDataset.Tables("test").NewRow()
'THIS SETS ALL OF THE COLUMNS IN THIS NEW ROW AS EQUAL TO ROW1 IN THE CSV DATATABLE
DB_row("Name") = CSV_row("Name")
DB_row("Quality") = CSV_row("Address")
DBDataset.Tables("test").Rows.Add(DB_row)
i = i + 1
Loop
mySqlDataAdapter.Update(DBDataset.Tables("Test"))

I managed to fix this myself after a fair bit of googling and some trial and error. Posting my code in case it's useful for anyone else
Craig
'MAKE A NEW SQL CONNECTION
Dim DBConnection As New SqlConnection
'SET THE CONNECTION STRING. YOU GET THIS BY GOING TO SERVER EXPLORER, THEN CLICKING ON THE DATABASE
'THE CONNECTION STRING IS IN PROPERTIES
DBConnection.ConnectionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\ME\Project\Members.mdf;Integrated Security=True"
'OPEN THE CONNECTION TO THE DATABASE
DBConnection.Open()
'THIS OPENS AN ADAPTER TO THE DATABASE, AND SELECTS EVERYTHING FROM THE 'TEST' TABLE IN THAT DATABASE
Dim mySqlDataAdapter As New SqlDataAdapter("SELECT * FROM MemberList", DBConnection)
'THIS LETS US USE SQL ON THE DATATABLE (IT GETS PASSED THE ABOVE SQL STATEMENT)
Dim mySqlCommandBuilder As New SqlCommandBuilder(mySqlDataAdapter)
'THIS MAKES ANOTHER NEW DATASET
Dim DBDataset As DataSet = New DataSet
''THIS FILLS THAT DATASET WITH THE TEST TABLE (WHICH THE DATA ADAPTOR GRABBED ABOVE)
mySqlDataAdapter.FillSchema(DBDataset, SchemaType.Source, "MemberList")
mySqlDataAdapter.Fill(DBDataset, "MemberList")
'THIS MAKES A NEW DATATABLE
'I THEN MAKE ALL CHANGES NEEDED
Dim EDITmembers As DataTable
EDITmembers = DBDataset.Tables("MemberList")
''FIRST, IM GOING TO CLEAR ALL ENTRIES IN THE DATATABLE (SO I CAN FILL IT FROM SCRATCH)
'COUNT THE NUMBER OF ENTRIES TO CLEAR
Dim RowsInDB As Integer
RowsInDB = EDITmembers.Rows.Count()
'SET UP A LOOP TO CLEAR THEM
Dim Data_row As DataRow
Dim k As Integer = 0
Do Until k = RowsInDB
Data_row = EDITmembers.Rows(k)
Data_row.Delete()
k = k + 1
Loop
'ONCE ALL THE ROWS ARE CLEARED, SAVE THE CHANGES BY UPDATING THE ACTUAL DATABASE
mySqlDataAdapter.Update(DBDataset, "MemberList")
''THEN I SET UP A LOOP TO ADD EACH RECORD FROM THE CSV DATATABLE TO THE DATABASE DATATABLE
''I FIRST NEED TO KNOW HOW MANY ITERATIONS OF THE LOOP TO DO
Dim CSV_row_number As Int16
'COUNT THE NUMBER OF ROWS AND SET THE ABOVE INT EQUAL TO THIS
CSV_row_number = ToLoad.Rows.Count
Dim j As Int16
j = 0
Do Until j = CSV_row_number - 1
'THIS MAKES TWO NEW DATAROW OBJECTS
Dim DB_row As DataRow
Dim CSV_row As DataRow
'THIS SETS THE CSV_ROW OBJECT EQUAL TO THE FIRST ROW OF THE CSV DATATABLE
CSV_row = ToLoad.Rows(j)
'THIS SETS DB_ROW EQUAL TO A NEW ROW IN THE DATATABLE MADE FROM THE DATABASE
DB_row = EDITmembers.NewRow()
'THIS SETS ALL OF THE COLUMNS IN THIS NEW ROW AS EQUAL TO THE CORRESPONDING ROW IN THE CSV DATATABLE
DB_row("Contact Name") = CSV_row("Contact Name")
DB_row("Do not mail") = CSV_row("Do not mail")
DB_row("Membership Type") = CSV_row("Membership Type")
DB_row("Street Address") = CSV_row("Street Address")
DB_row("Supplemental Address 1") = CSV_row("Supplemental Address 1")
DB_row("Supplemental Address 2") = CSV_row("Supplemental Address 2")
DB_row("City") = CSV_row("City")
DB_row("Postal Code") = CSV_row("Postal Code")
DB_row("Email") = CSV_row("Email")
DB_row("Phone (primary)") = CSV_row("Phone (primary)")
EDITmembers.Rows.Add(DB_row)
j = j + 1
Loop
'UPDATE THE DATABASE WITH ALL THE CHANGES
mySqlDataAdapter.Update(DBDataset, "MemberList")
MessageBox.Show("done!")

Related

VB form - to allow user interaction to select data from SQL Server

I am new to VB, just got started not long ago, and I am happy to be making progress.
However, I am more new to VB forms when connects to SQL server and allows user to interact with it to query out whatever data they wants into excel.
It begins like this, I've already created a userform that has checkbox (> than, < than), a textbox (input a number), and 2 other checkbox (male, female) and a combobox (state). I also already have the data in the SQL Server database.
What I am trying to do and is still trying is to allow users to interact with the form by checking the checkboxes, making selection in the combobox and inputting a number in the textbox and click on a button to run the VB program to export the requested data into Excel (my challenge is - it can export it into an Excel file that has already been created and saved in a directory or to export it into a newly created Excel file that has not been save yet (kind of like a pop-up).
For example - a user checks > than, and enter number 25 (btw this is age), and checks female and in combobox selects NY and click on a button. The program should query out, in this case, female over 25 that lives in NY and export it into Excel as a pop-up or an excel file that is already saved in a directory. I have been doing some research on this but hasn't made much progress as I am new to forms, connection and extraction. My code below creates an Excel file in a directory and is trying to query out the data into the save Excel file. My query is below too. Please advise !
Imports System.IO
Imports excel = Microsoft.office.interop.Excel
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.OleDb
Module module1
Dim myconnection As SqlConnection
Dim mycommand As SqlCommand
Sub main()
Dim xlapp = New excel.application
xlapp.visible = True
Dim xlwb As excel.workbook
Dim xlws As excel.worksheet
Dim path As String = "C:\users\t\"
Dim excel_name As String = "zp"
xlwb = xlapp.workbooks.add()
xlws = xlwb.sheets("sheet1")
xlwb.saves(path & excel_name)
xlapp.save()
xlapp.quit()
Using myconnection As New SqlConnection("data source =afe;initial catalog=zp;integrated securitytrue")
myconnection.Open()
Dim mycommand As New SqlCommand("insert into openrowset('Microsoft.ace.oledb.12.0','excel 12.0; database=zp:\c:users\dek\rep\zp.xlsx;','SELECT * FROM [Sheet1$]') select * from mem_TBL", myconnection)
End Using
End Sub
End Module
this is my query base on user selection as example.
SELECT a.z, a.ad, a.ag, a.ret, a.tot, a.wgt
FROM mtbl a INNER JOIN zTBL b ON a.z = b.zp
WHERE a.age > 25 AND a.ad = "NY" AND a.ret ="female"
This is the approach I use when exporting to Excel: I create a template of the Excel file that I will generate and save it in a fixed folder. When I export to excel, I:
copy the template file to a temporary folder
open the temporary file,
add the data to the temporary file,
close it,
save it to the destination file
delete the temporary file
Private Sub ExportToExcel()
Using myconnection As New SqlClient.SqlConnection("data source=afe;initial catalog=zp;integrated securitytrue")
myconnection.Open()
Dim mycommand As New SqlClient.SqlCommand("SELECT a.z, a.ad, a.ag, a.ret, a.tot, a.wgt FROM mtbl a INNER JOIN zTBL b ON a.z = b.zp WHERE a.age > #age AND a.ad = #state AND a.ret = #gender", myconnection)
mycommand.Parameters.AddWithValue("#age", 25)
mycommand.Parameters.AddWithValue("#state", "NY")
mycommand.Parameters.AddWithValue("#gender", "female")
Dim dataset As New DataSet
Dim adapter As New SqlClient.SqlDataAdapter(mycommand)
adapter.Fill(dataset, "data")
Dim xlapp = New Microsoft.Office.Interop.Excel.Application
xlapp.visible = True
Dim xlwb As Microsoft.Office.Interop.Excel.Workbook
Dim xlws As Microsoft.Office.Interop.Excel.Worksheet
Dim templatePath As String = "<path to template file>"
Dim path As String = "C:\users\t\"
Dim excel_name As String = "zp"
Dim tempFIle As String = templatePath & "\NAME OF YOUR TEMPLATE FILE INCLUDING EXTENSION"
xlwb = xlapp.Workbooks.Open(tempFIle)
xlws = CType(xlwb.Worksheets("Sheet1"), Microsoft.Office.Interop.Excel.Worksheet)
Dim rowIndex As Integer = 0
For Each row As DataRow In dataset.Tables(0).Rows
' since you alrady have a template,
' you already know the cell mapping of each column
' in your template file.
' Excel uses Row, Column to map cells and is 1-based
rowIndex += 1
xlapp.Cells(rowIndex, 1).Value = row("<name of column 1>")
xlapp.Cells(rowIndex, 2).Value = row("<name of column 2>")
xlapp.Cells(rowIndex, 3).Value = row("<name of column 3>")
xlapp.Cells(rowIndex, 4).Value = row("<name of column 4>")
'.
'.
'xlapp.Cells(rowIndex, N).Value = row("<name of column N>")
Next
xlapp.DisplayAlerts = False
xlwb.SaveAs(path & excel_name)
xlwb.Close()
xlapp.DisplayAlerts = True
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlwb)
xlapp.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlapp)
System.IO.File.Delete(tempFIle)
End Using
End Sub

vb.net listbox display tables names from database

I need to list all the tables in the list box from the database.mdb file. Not the contents of the tables just the tables name using Microsoft.Jet.OLEDB.4.0
I'm new to vb.net, please help.
this is what i have so far.. and i keep getting errors
Dim dbpath As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
dbpath = New Uri(dbpath).LocalPath
TextBox1.Text = dbpath + "\database.mdb"
Dim userTables As DataTable = Nothing
Dim connection As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection()
connection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; data source =" textbox1.text
' We only want user tables, not system tables
Dim restrictions() As String = New String(4) {}
restrictions(3) = "Table"
connection.Open()
' Get list of user tables
userTables = connection.GetSchema("Tables", restrictions)
connection.Close()
' Add list of table names to listBox
Dim i As Integer
For i = 0 To userTables.Rows.Count - 1 Step i + 1
ListBox1.Items.Add(userTables.Rows(i)(2).ToString())
Next
You can use the following code segment to display the list of tables in a .mdb file Click Here to get reference
Dim userTables As DataTable = Nothing
Dim connection As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection()
connection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;//your database path"
' We only want user tables, not system tables
Dim restrictions() As String = New String(4) {}
restrictions(3) = "Table"
connection.Open()
' Get list of user tables
userTables = connection.GetSchema("Tables", restrictions)
connection.Close()
' Add list of table names to listBox
Dim i As Integer
For i = 0 To userTables.Rows.Count - 1 Step i + 1
ListBox1.Items.Add(userTables.Rows(i)(2).ToString())
Next
seem this the right answer
Dim userTables As DataTable = Nothing
Dim connection As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection()
Dim source As String
source = TextDBPath.Text
connection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + source
Dim restrictions() As String = New String(3) {}
restrictions(3) = "Table"
connection.Open()
' Get list of user tables
userTables = connection.GetSchema("Tables", restrictions)
connection.Close()
' Add list of table names to listBox
Dim i As Integer
For i = 0 To userTables.Rows.Count - 1 Step i + 1
cbox.items.add(userTables.Rows(i)(2).ToString())
Next

Vb .net Error, No row in database greater than 0

I am making a vb .net winform project that uses a sql server database. A user inputs the details of a person (firstName, lastName, company, contactNumber, etc.) visiting a factory into textboxes, hits the save details button, and this saves the data in the datatable. This works fine, the problem is the next part. The user is then redirected to another form where the input details are shown from the database. This works for the first record but not for any record input after that, I get an error that says "There is no row at position 'n'" and the following line of code is highlighted in the form_Load:
txtFirstName.Text = CStr(dtVisitorDetails.Rows(CInt(CDbl(txtIdNumber.Text) - 1)).Item(1))
It is telling me that any rows after row 0 are not there but I know they are because I have input them and they are showing up in the datatable in the sql server database manager.
I cannot sort this problem, any help with this would be greatly appreciated. I am attaching the rest of the code that's involved with this problem.
Thanks in advanced.
Private Sub previousVisitor_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connectionString = "Data Source=.\SQLExpress;InitialCatalog=Visitors;" & _
"IntegratedSecurity=True;MultipleActiveResultSets=True"
sqlVisitorDetails = "SELECT * FROM visitorDetails WHERE idNumber=#idNumber"
sqlCon.Open()
sqlCmd = New SqlCommand(sqlVisitorDetails, sqlCon)
sqlCmd.Parameters.AddWithValue("#idNumber", txtIdNumber.Text)
dtVisitorDetails = loadDtVisitorDetails()
txtFirstName.Text = CStr(dtVisitorDetails.Rows(CInt(CDbl(txtIdNumber.Text) - 1)).Item(1))
txtLastName.Text = CStr(dtVisitorDetails.Rows(CInt(CDbl(txtIdNumber.Text) - 1)).Item(2))
txtCompany.Text = CStr(dtVisitorDetails.Rows(CInt(CDbl(txtIdNumber.Text) - 1)).Item(3))
txtContactNumber.Text = CStr(dtVisitorDetails.Rows(CInt(CDbl(txtIdNumber.Text) - 1)).Item(4))
txtCountryCode.Text = CStr(dtVisitorDetails.Rows(CInt(CDbl(txtIdNumber.Text) - 1)).Item(5))
txtEmail.Text = CStr(dtVisitorDetails.Rows(CInt(CDbl(txtIdNumber.Text) - 1)).Item(7))
sqlCmd.Dispose()
sqlCon.Close()
End Sub
Private Function loadDtVisitorDetails() As DataTable
Dim dtVisitorDetails As DataTable = Nothing
sqlVisitorDetails = "SELECT * FROM visitorDetails WHERE idNumber=" & txtIdNumber.Text
dtVisitorDetails = fillDtVisitorDetails(sqlVisitorDetails)
Return dtVisitorDetails
End Function
Public Function fillDtVisitorDetails(ByVal sqlVisitorDetails As String) As DataTable
Dim dtVisitorDetails As New DataTable
Dim da As New SqlDataAdapter
Dim conCmd As New SqlCommand
conCmd.CommandText = sqlVisitorDetails
da.SelectCommand = conCmd
da.SelectCommand.Connection = sqlCon
dtVisitorDetails.Columns.GetEnumerator()
da.Fill(dtVisitorDetails)
Return dtVisitorDetails
End Function
Since you can only have 1 row for each unique ID number, when you search and filter as WHERE idNumber = ID Number in form, you should get at most 1 record. That means the DataTable can have at most 1 row.
When you access the Rows of a DataTable like dt.Rows(ID), you are trying to access the row at position number ID in the collection of rows. Therefore, when you do dtVisitorDetails.Rows(CInt(CDbl(txtIdNumber.Text) - 1) for any value of ID number greater than 1, it will fail because that index simply does not exist in the table.
Instead, you should directly use dtVisitorDetails.Rows(0) to access the row. Since you have filtered by the ID Numberm you will only get the details for that person by doing so. Finally, remember to add a check for the row count in the table, so that if you search for an ID which has no records, there will not be an error in trying to retrieve from the table.
Pseudo-code:
If dtVisitorDetails.Rows.Count > 0
txtFirstName.Text = CStr(dtVisitorDetails.Rows(0).Item(1))
...
End If

Compare values in DGV column with database values and add value to new DGV column

So, Access database has two columns 1st is seller name (SELLER) and second is it's code (CODE). Access database is database with all SELLER CODEs.
DGV is populated from other source and consists of some of CODEs from Access database.
DGV has one column with codes.
I would like to create and populate new column (SELLERNAME) in DGV with SELLER names based on DGV codes and Access database CODEs.
I am going to give an example since it's hard for me to explain this better :
DGV : Column 0, 1st value = 0055, in Access database code 0055 corresponds to the name John
so I would like to put name "John" in DGV Column1, 1st value, nest to "0055" and so on
Here is my code so far :
DataGridView1.Columns.Add("SELLERNAME", "SELLERNAME") '1
Dim cn As OleDb.OleDbConnection
Dim cmd As OleDb.OleDbCommand
Dim odr As OleDb.OleDbDataReader
Dim strSQL As String
cn = New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\SCodes.MDB")
strSQL = "SELECT SELLER, CODE FROM SCBASE"
cn.Open()
cmd = New OleDb.OleDbCommand(strSQL, cn)
odr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Do While odr.Read
For i As Integer = 0 To DataGridView1.Rows.Count - 1
DataGridView1.Rows(i).Cells(1).Value = odr.GetValue(1).ToString()
Next
Loop
I don't know what to do next after line For i As Integer = 0 To DataGridView1.Rows.Count - 1.
EDIT :
I think I am close but I need help with one line of code :
Using sqlconn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\SCodes.mdb")
Using sqlcmd = New OleDbCommand("Select SELLER, CODE From SCBASE Where CODE = #CODE ", sqlconn)
sqlcmd.Parameters.AddWithValue("#CODE ", DataGridView1.Rows(i).Cells(0).Value) 'HOW TO ADD THIS LINE IN LOOP BELOW
sqlconn.Open()
Dim result = sqlcmd.ExecuteReader()
Do While (result.Read())
For i As Integer = 0 To DataGridView1.Rows.Count - 1
DataGridView1.Rows(i).Cells(1).Value = (result("DOBAVLJAC"))
Next
Loop
End Using
End Using
I had no success with a trial and error. I am trying to put this line sqlcmd.Parameters.AddWithValue("#CODE ", DataGridView1.Rows(i).Cells(0).Value) in loop below but I am getting all sorts of error.
Yes, you are very close. You just need to .Add the Parameter outside the loop and then set its .Value inside the loop like this
Using sqlconn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\SCodes.mdb")
sqlconn.Open()
Using sqlcmd = New OleDbCommand("Select SELLER, CODE From SCBASE Where CODE = ?", sqlconn)
sqlcmd.Parameters.Add("?", OleDbType.VarWChar, 255)
sqlcmd.Prepare()
For i As Integer = 0 To DataGridView1.Rows.Count - 1
sqlcmd.Parameters(0).Value = DataGridView1.Rows(i).Cells(0).Value
Using result = sqlcmd.ExecuteReader()
If result.Read() Then
DataGridView1.Rows(i).Cells(1).Value = result("SELLER")
End If
End Using
Next
End Using
End Using

Import records from CSV file into SQL Server 2008 R2 using VB .Net 2010

I need to import records from a comma delimited CSV file into an existing table in SQL Server R2 database using Visual Basic .Net 2010. Existing records in the table are to be deleted prior to import. I have been able to create an in-memory temporary DataTable and populate the records from CSV file using TextFieldParser. I have checked it by binding the in-memory DataTable to a DataGridView. But I am clueless in the second part i.e. how to insert records into the SQL table from the in-memory DataTable.
I have done the following:
`Dim TextFileReader As New TextFieldParser("C:\csvtosql\StockVB\VFPFiles\ExpSysusers.csv")
TextFileReader.TextFieldType = FileIO.FieldType.Delimited
TextFileReader.SetDelimiters(",")
Dim TextFileTable As DataTable = Nothing
Dim Column As DataColumn
Dim Row As DataRow
Dim UpperBound As Int32
Dim ColumnCount As Int32
Dim CurrentRow As String()
CurrentRow = TextFileReader.ReadFields() ' Ignore the header
While Not TextFileReader.EndOfData
Try
CurrentRow = TextFileReader.ReadFields()
If Not CurrentRow Is Nothing Then
''# Check if DataTable has been created
If TextFileTable Is Nothing Then
TextFileTable = New DataTable("TextFileTable")
''# Get number of columns
UpperBound = CurrentRow.GetUpperBound(0)
''# Create new DataTable
For ColumnCount = 0 To UpperBound
Column = New DataColumn()
Column.DataType = System.Type.GetType("System.String")
Column.ColumnName = "Column" & ColumnCount
Column.Caption = "Column" & ColumnCount
Column.ReadOnly = True
Column.Unique = False
TextFileTable.Columns.Add(Column)
Next
End If
Row = TextFileTable.NewRow
For ColumnCount = 0 To UpperBound
Row("Column" & ColumnCount) = CurrentRow(ColumnCount).ToString
Next
TextFileTable.Rows.Add(Row)
End If
Catch ex As Exception
MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
End Try
End While
TextFileReader.Dispose()
DataGridView1.DataSource = TextFileTable
`
Can anybody please help/guide me??
I tried the following code to read the records from the DataTable and insert into the SQL Table. But it seems that only the first record is being added.
For Each TextFileTableDataRow As DataRow In TextFileTable.Rows
Dim Column0 As String = TextFileTableDataRow("Column0")
Dim Column1 As String = TextFileTableDataRow("Column1")
Dim Column2 As Int16 = TextFileTableDataRow("Column2")
Dim Column3 As Boolean = TextFileTableDataRow("Column3")
Dim strSqlQry As String = "INSERT INTO Personnel (Operator,OpPassword,SecurityLevel,Active) VALUES (#Operator,#OpPassword,,#SecurityLevel,#Active)"
Dim SqlconnectionString As String = gcconnect
Using connection As New SqlClient.SqlConnection(SqlconnectionString)
Dim cmd As New SqlClient.SqlCommand(strSqlQry, connection)
' create command objects and add parameters
With cmd.Parameters
.AddWithValue("#Operator", Column0)
.AddWithValue("#OpPassword", Column1)
.AddWithValue("#SecurityLevel", Column3)
.AddWithValue("#LoggedOn", Column7)
End With
Dim adapter As New SqlClient.SqlDataAdapter()
adapter.InsertCommand = cmd
'--Update the original SQL table from the datatable
Dim iRowsInserted As Int32 = adapter.Update(TextFileTable)
End Using
Next
I am getting the following error:
"Violation of PRIMARY KEY Constraint 'PK_Personnel'. Cannot insert duplicate key in object 'dbo.Personnel'."

Resources