Database update will not work - c#-to-vb.net

I know that you guys will find this simple, but can anyone tell me why I am getting a syntax error despite following every instruction on numerous sites?
My code in full is:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = F:\Brett\Programming Projects\Roster\Roster.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
' This is grabbing all the records from the listing table in the Roster Database
sql = "Select * FROM Listing"
' Or selected columns
'sql = "SELECT Listing.FName, Listing.LName FROM Listing"
da = New OleDb.OleDbDataAdapter(sql, con)
' Populate the dataset with the data adaptor. This can be any name
da.Fill(ds, "Roster")
con.Close()
MaxRows = ds.Tables("Roster").Rows.Count
inc = -1
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim iRow As Integer = Me.Label1.Text
Dim junk As Integer
ds.Tables("Roster").Rows(iRow).Item(5) = Me.TextBox3.Text
ds.Tables("Roster").Rows(iRow).Item(6) = Me.TextBox4.Text
ds.Tables("Roster").Rows(iRow).Item(8) = Me.TextBox5.Text
da.Update(ds, "Roster")
'da.Update(ds)
End Sub
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim newtbl As DataTable
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim cmd As New OleDb.OleDbCommand
newtbl = ds.Tables("Roster")
Dim drCurrent As DataRow
drCurrent = newtbl.NewRow()
drCurrent(1) = "sfd"
drCurrent(2) = "werter"
newtbl.Rows.Add(drCurrent)
da.Update(ds, "Roster")
End Sub
No matter what I do, I get this error message. Any help will be greatly appreciated as this is two days now...
I would show you my error but as usual, some peanut won't let me without some crap.. It states OleDbException was unhandled, Syntax error in Insert Into statement.

Can you try wrapping your database calls in a try-catch block and inspect the InnerXml that's returned with the exception?
That might give you more information about the error that you're getting.

Related

Update the database from the GridView when the data source is a query

I have SQL QUERY:
SELECT T_DATA_LOG.ID, T_DATA_LOG.SerialNumber, T_DATA_LOG.Note, T_EVENT.Name
FROM T_DATA_LOG INNER JOIN T_EVENT ON T_DATA_LOG.ID_EVENT = T_EVENT.ID_EVENT;
Table T_DATA_EVENT is event catalog for T_DATA_LOG
I need update T_DATA_LOG.Note
I have this program. If I work directly with a spreadsheet, it works. if I use a query (join two tables) as a data source, it doesn't work.
Imports System.Data.OleDb
Public Class
Dim connetionString As String
Dim connection As OleDbConnection
Dim adapter As OleDbDataAdapter
Dim cmdBuilder As OleDbCommandBuilder
Dim ds As New DataSet
Dim changes As DataSet
Dim sql As String
Dim i As Int32
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'connetionString = "Data Source=Server_Name\SQLEXPRESS;Initial Catalog=Test;Trusted_Connection=True;"
connetionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & "e:\tmp\KuKacka2.0.accdb;Persist Security Info=False;"
connection = New OleDbConnection(connetionString)
'sql = "Select * from D_DATA_LOG" - This is Work, but I need view data from T_EVENT
sql = "SELECT T_DATA_LOG.ID, T_DATA_LOG.SerialNumber, T_DATA_LOG.Note, T_EVENT.Name FROM T_DATA_LOG INNER JOIN T_EVENT ON T_DATA_LOG.ID_EVENT = T_EVENT.ID_EVENT;"
Try
connection.Open()
adapter = New OleDbDataAdapter(sql, connection)
adapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
connection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub DataGridView1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles DataGridView1.Click
DataGridView1.DefaultCellStyle.SelectionBackColor = Color.Orange
End Sub
Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'NOTE: for this code to work, there must be a PK on the Table
Try
cmdBuilder = New OleDbCommandBuilder(adapter)
changes = ds.GetChanges()
If changes IsNot Nothing Then
adapter.Update(changes)
End If
MsgBox("Changes Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
Please, give me an advice.
Thanks, David

System.Data.SqlClient.SqlException: 'Incorrect syntax near '​'.'

I get this SQL Server error and I can't figure out where the trouble is:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
xception Details: System.Data.SqlClient.SqlException: 'Incorrect syntax near '​'.'
Source Error: Line: 46
Error Line: cmdsql.ExecuteNonQuery()
Code:
Dim connexcel As OleDbConnection
Dim daexcel As OleDbDataAdapter
Dim dsexcel As DataSet
Dim cmdexcel As OleDbCommand
Dim drexcel As OleDbDataReader
Dim connsql As SqlConnection
Dim dasql As SqlDataAdapter
Dim dssql As DataSet
Dim cmdsql As SqlCommand
Dim drsql As SqlDataReader
Private Sub import_excel_to_sql_server_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.CenterToScreen()
End Sub
Private Sub BtnImpExcelFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnImpExcelFile.Click
On Error Resume Next
OpenFileDialog1.Filter = "(* .xls) | * .xls | (*. Xlsx) | *. xlsx | All files (*. *) | *. * "
OpenFileDialog1.ShowDialog()
FileAdd.Text = OpenFileDialog1.FileName
connexcel = New OleDbConnection("provider = Microsoft.ace.OLEDB.12.0; data source =" & FileAdd.Text & "; Extended Properties = Excel 8.0;")
connexcel.Open()
Dim dtSheets As DataTable = connexcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
listSheet.Add(drSheet("TABLE_NAME").ToString())
Next
For Each sheet As String In listSheet
ExcelSheetList.Items.Add(sheet)
Next
End Sub
Private Sub ExcelSheetList_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExcelSheetList.SelectedIndexChanged
daexcel = New OleDbDataAdapter("select * from [" & ExcelSheetList.Text & "]", connexcel)
dsexcel = New DataSet
daexcel.Fill(dsexcel)
DGVImpData.DataSource = dsexcel.Tables(0)
DGVImpData.ReadOnly = True
End Sub
Sub connections()
connsql = New SqlConnection("data source =. \ MSSMLBIZ; initial catalog = MyInvoice; integrated security = true")
connsql.Open()
End Sub
Private Sub BtnSaveImpData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSaveImpData.Click
For line As Integer = 0 To DGVImpData.RowCount - 2
Call connections()
Dim save As String = "insert into InvoiceData values ​​('" & DGVImpData.Rows(line).Cells(0).Value & "', '" & DGVImpData.Rows(line).Cells(1).Value & "')"
cmdsql = New SqlCommand(save, connsql)
cmdsql.ExecuteNonQuery()
Next
MsgBox("data saved successfully")
DGVImpData.Columns.Clear()
End Sub
Keep your database objects local so you can be sure they are closed and disposed. Enclosing these objects with `Using...End Using blocks will accomplish this even if there is an error. You don't need variables for DataAdapters, DataSets, or DataReaders. I suggest only one form level variable for the Excel connection string since it is used in 2 methods.
A little bit of Linq will get the retrieved sheet names from the DataTable and fill an array. The array can then be passed to the list box with .AddRange.
I wouldn't use the SelectedIndexChanged event because the user can too easily click the wrong sheet or change their mind. I used a Button.Click event to fill the grid.
The Sql connection string looks strange to me. I suggest you test it separately. If it doesn't work, this is a good resource. https://www.connectionstrings.com/
I would specifically state the column names in the Insert statement. Replace FirstColumnName and SecondColumnName with the real column names. The parameter names can be anything you wish as long as the names in the statement match the names in the Parameters.Add method. I have guessed at the datatypes and the size. Check your database for correct values.
We add the parameters only once outside the loop then change only values inside the loop.
Private ExcelConString As String
Private Sub BtnImpExcelFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnImpExcelFile.Click
Dim strFileName As String
Dim dtSheets As DataTable
OpenFileDialog1.Filter = "(* .xls) | * .xls | (*. Xlsx) | *. xlsx | All files (*. *) | *. * "
OpenFileDialog1.ShowDialog()
strFileName = OpenFileDialog1.FileName
ExcelConString = "provider = Microsoft.ace.OLEDB.12.0; data source =" & strFileName & "; Extended Properties = Excel 8.0;"
Using connexcel = New OleDbConnection(ExcelConString)
connexcel.Open()
dtSheets = connexcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
End Using
Dim exSheets() As Object = (From dRow In dtSheets.AsEnumerable() Select dRow("TABLE_Name")).ToArray
ExcelSheetList.Items.AddRange(exSheets)
End Sub
Private Sub DisplayData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DisplayData.Click
Dim dt As New DataTable
Using cn As New OleDbConnection(ExcelConString)
'In older versions of Visual Studio you may have to use String.Format instead of the interpolated string.
Using cmd As New OleDbCommand($"select * from [{ExcelSheetList.Text}];", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
DGVImpData.DataSource = dt
DGVImpData.ReadOnly = True
End Sub
Private Sub BtnSaveImpData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSaveImpData.Click
Using cn As New SqlConnection("data source =. \ MSSMLBIZ; initial catalog = MyInvoice; integrated security = true")
Using cmd As New SqlCommand("Insert Into InvoiceData (FirstColumnName, SecondColumnName) Values ​​(#FirstColumn, #SecondColumn);", cn)
cmd.Parameters.Add("#FirstColumn", SqlDbType.VarChar, 100)
cmd.Parameters.Add("#SecondColumn", SqlDbType.VarChar, 100)
cn.Open()
For line As Integer = 0 To DGVImpData.RowCount - 2
cmd.Parameters("#FirstColumn").Value = DGVImpData.Rows(line).Cells(0).Value
cmd.Parameters("#SecondColumn").Value = DGVImpData.Rows(line).Cells(1).Value
cmd.ExecuteNonQuery()
Next
End Using
End Using
MsgBox("data saved successfully")
DGVImpData.Columns.Clear()
End Sub
As to error handling... On Error Resume Next is generally not used in new code. We have Try...Catch...Finally blocks. After your code is running add these blocks where needed.
EDIT
To use String.Format...
Using cmd As New OleDbCommand(String.Format("select * from [{0}];", ExcelSheetList.Text))
The first parameter is the string in which you wish to place variables. It contains indexed placeholders enclosed in braces. The following parameters are the variables you want for the placeholder substitution.
Thank you for helping me to a fixed error in my code. Here is Final code without System.Data.SqlClient.SqlException: 'Incorrect syntax near '​'.' error.
Now I tried to improve code with the last section(mention below) to define parameters for exporting data. Because I have a large number of data for exporting to SQL Server I get a Timeout error. Can anyone be able to improve code for quick exporting data to SQL Server?
connsql.Open() "System.InvalidOperationException: 'Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.'"
Dim connexcel As OleDbConnection
Dim daexcel As OleDbDataAdapter
Dim dsexcel As DataSet
Dim cmdexcel As OleDbCommand
Dim drexcel As OleDbDataReader
Dim connsql As SqlConnection
Dim dasql As SqlDataAdapter
Dim dssql As DataSet
Dim cmdsql As SqlCommand
Dim drsql As SqlDataReader
Private Sub Import_excel_to_sql_server_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.CenterToScreen()
End Sub
Private Sub PKGAbtnImpExcelFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PKGAbtnImpExcelFile.Click
On Error Resume Next
'OpenFileDialog1.Filter = "(*.xls)|*.xls|(*.xlsx)|*.xlsx|All files (*.*)|*.*"
PKGAofdImpOpenExcel.ShowDialog()
PKGAtxtImpFileAdd.Text = PKGAofdImpOpenExcel.FileName
connexcel = New OleDbConnection("provider=Microsoft.ace.OLEDB.12.0;data source=" & PKGAtxtImpFileAdd.Text & ";Extended Properties=Excel 8.0;")
connexcel.Open()
Dim dtSheets As DataTable = connexcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
listSheet.Add(drSheet("TABLE_NAME").ToString())
Next
For Each sheet As String In listSheet
PKGAtxtImpExlSheetL.Items.Add(sheet)
Next
End Sub
Private Sub PKGAtxtImpExlSheetL_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PKGAtxtImpExlSheetL.SelectedIndexChanged
daexcel = New OleDbDataAdapter("select * from [" & PKGAtxtImpExlSheetL.Text & "]", connexcel)
dsexcel = New DataSet
daexcel.Fill(dsexcel)
PKGAdgvImpData.DataSource = dsexcel.Tables(0)
PKGAdgvImpData.ReadOnly = True
End Sub
'Last Section
Sub Connectonsql()
connsql = New SqlConnection("Data Source=DESKTOP-MIQGJTK\MSSMLBIZ;Initial Catalog=PkGlobalAccounting;Integrated Security=True")
connsql.Open()
End Sub
Private Sub PKGAbtnImpSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PKGAbtnImpSave.Click
For Line As Integer = 0 To PKGAdgvImpData.RowCount - 2
Call Connectonsql()
Dim save As String = "insert into Test values('" & PKGAdgvImpData.Rows(Line).Cells(0).Value & "','" & PKGAdgvImpData.Rows(Line).Cells(1).Value & "')"
cmdsql = New SqlCommand(save, connsql)
cmdsql.ExecuteNonQuery()
Next
MsgBox("Data Saved Successfully")
PKGAdgvImpData.Columns.Clear()
End Sub
Thanks for Your Help.

Using VB.Net to Insert Data to an Access Database

Does anyone have an idea on how to update the actual access datbase file? This is my code so far and I think everything is right, but when hit the button to send the information to the actual database file it does not appear in there. Can someone help me with this? The access file I'm talking about is the one outside of the visual basic project itself, but still connected.
Code
Imports System.Data.OleDb
Public Class Form1
Dim provider As String
Dim datafile As String
Dim connString As String
Dim con As New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source=G:\Music Session Database\Music Database.accdb")
Dim ds As New DataSet
Dim dt As New DataTable
Dim da As New OleDbDataAdapter
Private Sub btnexit_Click(sender As Object, e As EventArgs) Handles btnexit.Click
Me.Close()
End Sub
Private Sub btnsubmit_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnsubmit1.Click
Me.Music_DatabaseTableAdapter.Insert(Me.songTitle.Text, Me.songArtist.Text, Me.songAlbum.Text, Me.yearReleased.Text)
Me.Music_DatabaseTableAdapter.Fill(Me.Music_DatabaseDataSet.Music_Database)
con.Open()
MsgBox("Record Added")
con.Close()
songTitle.Text = ""
songArtist.Text = ""
songAlbum.Text = ""
yearReleased.Text = ""
End Sub
Private Sub btnsumbit2_Click(sender As Object, e As EventArgs) Handles btnsumbit2.Click
Me.Play_SessionTableAdapter.Insert(Me.songTitle.Text, Me.songArtist.Text, Me.songAlbum.Text, Me.yearReleased.Text, Me.datePlayed.Text, Me.timePlayed.Text, Me.genre.Text)
Me.Play_SessionTableAdapter.Fill(Me.Music_DatabaseDataSet.Play_Session)
con.Open()
MsgBox("Record Added")
con.Close()
songTitle.Text = ""
songArtist.Text = ""
songAlbum.Text = ""
yearReleased.Text = ""
datePlayed.Text = ""
timePlayed.Text = ""
genre.Text = ""
End Sub
Private Sub btnsubmit3_Click(sender As Object, e As EventArgs) Handles btnsubmit3.Click
Me.Song_Artist_InformationTableAdapter.Insert(Me.songArtist.Text, Me.genre.Text, Me.origin.Text, Me.artistInformation.Text)
Me.Song_Artist_InformationTableAdapter.Fill(Me.Music_DatabaseDataSet.Song_Artist_Information)
con.Open()
MsgBox("Record Added")
con.Close()
songArtist.Text = ""
genre.Text = ""
origin.Text = ""
artistInformation.Text = ""
End Sub
Private Sub btnclear_Click(sender As Object, e As EventArgs) Handles btnclear.Click
songTitle.Clear()
songArtist.Clear()
songAlbum.Clear()
yearReleased.Clear()
datePlayed.Clear()
timePlayed.Clear()
genre.Clear()
artistInformation.Clear()
End Sub
Private Sub FillByToolStripButton_Click(sender As Object, e As EventArgs)
Try
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub Music_DatabaseBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles Music_DatabaseBindingNavigatorSaveItem.Click
Me.Validate()
Me.Music_DatabaseBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.Music_DatabaseDataSet)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Music_DatabaseDataSet.Song_Artist_Information' table. You can move, or remove it, as needed.
Me.Song_Artist_InformationTableAdapter.Fill(Me.Music_DatabaseDataSet.Song_Artist_Information)
'TODO: This line of code loads data into the 'Music_DatabaseDataSet.Play_Session' table. You can move, or remove it, as needed.
Me.Play_SessionTableAdapter.Fill(Me.Music_DatabaseDataSet.Play_Session)
'TODO: This line of code loads data into the 'Music_DatabaseDataSet.Music_Database' table. You can move, or remove it, as needed.
Me.Music_DatabaseTableAdapter.Fill(Me.Music_DatabaseDataSet.Music_Database)
End Sub
Private Sub btnupdate1_Click(sender As Object, e As EventArgs) Handles btnupdate1.Click
Me.Validate()
con.Open()
ds.Tables.Add(dt)
da = New OleDbDataAdapter("Select * from [Music Database]", con)
Dim cb = New OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
da.Fill(dt)
Music_DatabaseDataGridView.DataSource = dt.DefaultView
da.Update(dt)
End Sub
Private Sub btnupdate2_Click(sender As Object, e As EventArgs) Handles btnupdate2.Click
Me.Validate()
con.Open()
ds.Tables.Add(dt)
da = New OleDbDataAdapter("Select * from [Play Session]", con)
Dim cb = New OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
da.Fill(dt)
Play_SessionDataGridView.DataSource = dt.DefaultView
da.Update(dt)
End Sub
Private Sub btnupdate3_Click(sender As Object, e As EventArgs) Handles btnupdate3.Click
Me.Validate()
con.Open()
ds.Tables.Add(dt)
da = New OleDbDataAdapter("Select * from [Song Artist Information]", con)
Dim cb = New OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
da.Fill(dt)
Song_Artist_InformationDataGridView.DataSource = dt.DefaultView
da.Update(dt)
End Sub
End Class
Format of the initialization string does not conform to specification
The connString you create is not valid.
provider = "Microsoft.ACE.OLEDB.12.0"
datafile = "H:\Music Session Database\Music Database.accdb"
connString = provider & datafile
Console.WriteLine(connString)
shows
Microsoft.ACE.OLEDB.12.0H:\Music Session Database\Music Database.accdb
What you want to do is something like
connString = String.Format("Provider={0};Data Source={1}", provider, datafile)
which produces
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\Music Session Database\Music Database.accdb

How match system time with access database time?

I am creating an app in VB.NET that will play a song on user given time. User store song location and play time in ms-access database. when system time match with database time the song will play automatically. I've tried this with given below code but this is not working.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button1.Click
Me.Timer1.Start()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Timer1.Tick
Call Play(Format(Now, "Long Time"))
End Sub
Sub Play(ByVal tm As String)
Dim ConnectionString As String
ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=" & Application.StartupPath & "\VideoPlay.accdb;"
Dim AccessConnection As New
System.Data.OleDb.OleDbConnection(ConnectionString)
AccessConnection.Open()
Dim da As New System.Data.OleDb.OleDbDataAdapter("SELECT *
FROM VideoPlay", AccessConnection)
Dim ds As New DataSet
da.Fill(ds, "VideoPlay")
Dim dt As DataTable
dt = ds.Tables("VideoPlay")
Dim x As Integer
If dt.Rows.Count > 0 Then
For x = 0 To dt.Rows.Count - 1
If tm = dt.Rows(x).Item("TM") Then
MsgBox("yes")
End If
Next
End If
AccessConnection.Close()
da.Dispose()
ds.Dispose()
dt.Dispose()
AccessConnection.Close()
End Sub
End Class
Can any one tell me what is wrong in my code or any other way to compare system time with database time.
thanks in advance.

How to declare a connection object on a class level connection not in local scope with VB.NET?

I got the error:
Fill: SelectCommand.Connection property has not been initialized.
I think this is because I declare my data set not inside the private sub but in the public class.....
but I need to use the data set in more than once in different private sub during the program....how should I define it ?
many thanks.
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim con As SqlConnection
Dim strsql As String
Dim da As New SqlDataAdapter(strsql, con)
Dim ds As New DataSet()
Dim strcon As String
Dim newmode As Boolean
Dim newrow As DataRow
Dim cb As SqlCommandBuilder
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
newmode = False
'Dim con As SqlConnection
'Dim strsql As String
con = New SqlConnection("initial catalog=test;data source=nazi;integrated security=sspi;")
strsql = "select*from table_1"
con.Open()
'Dim da As New SqlDataAdapter(strsql, con)
'Dim ds As New DataSet()
da.Fill(ds, "dd")
TextBox1.DataBindings.Add(New Binding("text", ds, "dd.tel"))
TextBox2.DataBindings.Add(New Binding("text", ds, "dd.nam"))
TextBox3.DataBindings.Add(New Binding("text", ds, "dd.address"))
da.update(ds, "dd")
con.Close()
End Sub
Private Sub empty()
textrecord.text = ""
TextBox1.text = ""
TextBox2.text = ""
TextBox3.text = ""
TextBox4.text = ""
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
newrow = ds.Tables("dd").NewRow
newmode = True
textrecord.BackColor = Color.Red
textrecord.Text = "new record"
MsgBox("enter new record and press save")
Call empty()
End Sub
End Class
Instead of:
Dim con As SqlConnection
try adding New:
Dim con As New SqlConnection("initial catalog=test;...")
However, it's best practice to only open a connection just before you need it, and close it right after. Connections should be local variables in Using blocks, not class variables!
You create the DataAdapter at the global level in this line
Dim da As New SqlDataAdapter(strsql, con)
but at this point in time your strsql is empty and if you change it afterwards it doesn't change inside the dataadatpter, thus the error message.
If you insist on keeping all that global vars (and it's considered a bad practice as #Andomar pointed out in is answer) then you should be sure to create the DataAdapter with the correct sqlstring just before its usage:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
newmode = False
con = New SqlConnection("initial catalog=test;data source=nazi;integrated security=sspi;")
strsql = "select*from table_1"
con.Open()
da = New SqlDataAdapter(strsql, con) '<- added this line here '
da.Fill(ds, "dd")
....
con.Close()
End Sub

Resources