“The ConnectionString property has not been initialized” error in VB.NET - vb.net

Every time I tried to connect to the database it give me this error "The ConnectionString property has not been initialized"
How can i avoid this error and make it work?
Here are my codes:
Imports System.Data.OleDb
Public Class frmLoginPage
Dim con As New OleDbConnection
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim dt As New DataTable
Dim ds As New DataSet
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter
da = New OleDbDataAdapter("Select*from tblPassword", con)
da.Fill(dt)
Dim newRow As DataRow = dt.NewRow
With newRow
If .Item("Username") = txtUsername.Text And .Item("Password") = txtPassword.Text Then frmMainMenu.ShowDialog() Else MsgBox("The username or password you entered was incorrect, please try again!", MsgBoxStyle.Critical, "Information")
End With
End Sub

You have instantiated an OleDbConnection object, but you haven't set the connectionstring property so it doesn't know where it should connect to. You also haven't opened it. Your code should look something like:
Dim myConnection As OleDbConnection = New OleDbConnection()
myConnection.ConnectionString = myConnectionString
myConnection.Open()
' execute queries, etc
myConnection.Close()

This Problem Occurs when you donot consider making a new connection
The solution is very simple, all you have to do is to make
Dim conString as string = "Your connection string here"
Dim con As new OleDbConnection
con.connectionSting= ConSting
con.open()
'now simply write the query you want to be executed
'At the end write
con.close()
this will solve your problem.
if it doesn't solve your problem post reply I will try to solve it.

You never assigned your connection string to the connection object, just like the error is saying.
Insert a line setting the connection string before con.open.
Con.connectionstring = connection
Con.Open()
Or better yet, change your using statement as follows
Dim Connection As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=G:\VB Project\Library Catalog System\Library Catalog System\library.mdf;Integrated
Security=True;Connect Timeout=30;User Instance=True"
Using Con As New SqlConnection(connection)

Related

Load data into DataGridView from sql server in vb

Loading data from SQL server into datagridview but Warning 1 Variable 'dtApplicantLists' is used before it has been assigned a value. A null reference exception could result in runtime. green underline at dtApplicantLists.Load(reader)
Any help, please...
Private Function GetList() As DataTable
Dim dtApplicantLists As DataTable
Dim connString As String = ConfigurationManager.ConnectionStrings("dbx").ConnectionString
Using conn As New SqlConnection(connString)
Using cmmd As New SqlCommand("SELECT FirstName, LastName, Gender, ChosenProg, Aggregate FROM dbo.Applicants", conn)
conn.Open()
Dim reader As SqlDataReader = cmmd.ExecuteReader()
dtApplicantLists.Load(reader)
End Using
End Using
Return dtApplicantLists
End Function
You need to call dtApplicantLists = New DataTable - currently it is null (or Nothing in VB).
Using ... End Using Method will guarantee you won't need to worry about warnings like this one you got, as obviously demonstrated in your Code.
Private Function GetList() As DataTable
Dim SqlStr As String =
("SELECT FirstName, LastName, Gender, ChosenProg, Aggregate FROM dbo.Applicants")
Using dtApplicantLists As DataTable = New DataTable
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("dbx").ConnectionString),
Cmd As New SqlCommand(SqlStr, conn)
conn.Open()
Using Reader As SqlDataReader = Cmd.ExecuteReader
dtApplicantLists.Load(Reader)
End Using
End Using
Return dtApplicantLists
End Using
End Function
You can do it this way.
Imports System.Data.SqlClient
Public Class Form1
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim cmdBuilder As SqlCommandBuilder
Dim ds As New DataSet
Dim changes As DataSet
Dim sql As String
Dim i As Int32
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
connection = New SqlConnection(connetionString)
Sql = "select * from Product"
Try
connection.Open()
adapter = New SqlDataAdapter(Sql, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.Data Source= ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
cmdBuilder = New SqlCommandBuilder(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
See the link below for some other similar, but slightly different options.
http://vb.net-informations.com/dataadapter/dataadapter-datagridview-sqlserver.htm

How to feed results of SQL statement into a GridView, not the SQL statement itself?

This has got to be close, but it's been a long day and I'm tired now so I can;t really see what the problem is. Basically, I have a table in SQL Server with 2 columns; one has the names of reports and the other has some SQL Scripts that I want to pass into a GridView, based on what a user selects from a ListBox. Here is my code.
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim sqlConn As New SqlClient.SqlConnection("Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True")
sqlConn.Open()
Dim cmd As New SqlClient.SqlCommand("Select ReportName From [Table_1] order by ReportName", sqlConn)
Dim dsColumns As New DataSet
Dim daAdapter As New SqlClient.SqlDataAdapter(cmd)
daAdapter.Fill(dsColumns)
If dsColumns.Tables(0).Rows.Count > 0 Then
ListBox1.Items.Clear()
For i As Integer = 0 To dsColumns.Tables(0).Rows.Count - 1
ListBox1.Items.Add(dsColumns.Tables(0).Rows(i)(0).ToString())
Next
End If
Catch ex As Exception
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connetionString As String
Dim SqlStr As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim ds As New DataSet
Dim myItem As String
connetionString = "Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True"
connection = New SqlConnection(connetionString)
'Dim iIndex As Integer = ListBox1.SelectedIndex
myItem = ListBox1.SelectedItem
SqlStr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
Try
connection.Open()
adapter = New SqlDataAdapter(SqlStr, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
I guess the problem is passing the SQL to the GridView. When I select the first Item, I see this in my GridView.
SELECT [OrderID]
,[CustomerID]
,[EmployeeID]
,[OrderDate]
,[RequiredDate]
,[ShippedDate]
,[ShipVia]
,[Freight]
,[ShipName]
,[ShipAddress]
,[ShipCity]
,[ShipRegion]
,[ShipPostalCode]
,[ShipCountry]
FROM [Test].[dbo].[Orders]
That's pretty close, but I want to get that SQL fed into the GridView, and get the results of the SQL displayed in the GridView, not eh SQL statement itself.
This is what I see now.
I want to see something more like this.
Finally, I am curious to know of the GridView can be made dynamic, so if I stretch out the window the GridView shows more columns. Now, if I stretch out the form window, the GridView stays static.
You need to actually run the retrieved Sql statement:
sqlstr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
Try
connection.Open()
Dim cmd As New SqlCommand(sqlstr, connection)
Dim sqlstr_report As String = CStr(cmd.ExecuteScalar())
cmd.Dispose()
adapter = New SqlDataAdapter(sqlstr_report, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.DataSource = ds.Tables(0)
Use the .Anchor property of the DataGridView to make it resize with the form

Cannot Add new row to database with DataAdapter.insertCommand vb.net

I try to add new record to the database with command DataAdapter.InsertCommand. But I don't know why It doesn't insert new record to database
Here is my code:
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim cnn As New OleDb.OleDbConnection
Dim cmd As New OleDb.OleDbCommand
Dim da As New OleDb.OleDbDataAdapter
Dim ds As New DataSet
Dim dt As New DataTable
cnn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\1_Project\Project_of_VB_Net\AccessDatabase\StudentDatabase.accdb"
cmd.Connection = cnn
cmd.CommandText = "INSERT INTO StudentData(StudentID) VALUES (#studentid)"
cmd.Parameters.AddWithValue("#studentid", "123")
Try
cnn.Open()
da.InsertCommand = cmd
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
cnn.Close()
End Try
End Sub
Please help me find out what's wrong with it?
I'm all in favor of using what works and I see the solution above works. The advantage of using a dataadapter however, is that it wraps all the sql commands needed for the CRUD operations of the datatable. You can configure your own commands or let visual studio configure them automatically by using a sqlcommandbuilder. Then once you have the adapter configured all you need to do is something like this
Dim myds As New DataSet()
Dim mytable as New datatable()
myds.Tables.Add(mytable)
Dim myconstr As String = "ConnectionStringtoDataBase"
Dim myconn As New SqlConnection(myconstr)
Dim da as new SqlDataAdapter( “SELECT * FROM StudentTable”,cnn)
Dim mycb As New SqlCommandBuilder(da)
da.Fill(mytable)
Dim myrow As DataRow = mytable.NewRow()
myrow("ID") = "thestudentid"
myrow("StudentName") = "John doe"
myrow("StudentID") = 12345
myrow("StudentClass") = "VB 101"
mytable.Rows.Add(myrow)
da.Update(mytable)
The CommandBuilder will automatically add insert, update and delete commands to the dataadapter (if your select command is one table only, otherwise you'll have to configure it manually).

Overload resolution failed because no accessible 'Item' accepts this number of arguments

Making a small page that calls a SQL stored Proc with only one parameter, which the user would enter in a text box. In declaring that parameter, it is giving me the error above. Can anyone assist? The error is on the CMD.Parameters line..
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim CMD As New SqlCommand("daily_revenue_rerun")
CMD.Parameters("#date", SqlDbType.DateTime).value = TextBox1.Text
Dim connection As SqlConnection = New SqlConnection
connection.ConnectionString = "Data Source=azda-sql0;Persist Security Info=True;User ID=sa;Password=Sql#dm!n;Initial Catalog=RevenueTrakSQL"
CMD.Connection = connection
CMD.CommandType = CommandType.StoredProcedure
Dim Adapter As New SqlDataAdapter(CMD)
Dim DS As DataSet
Adapter.Fill(DS)
connection.Close()
End Sub
Thanks for any assistance..
Look at your parameter binding. What I can see is that your stored proc daily_revenue_rerun expects a DATETIME datatype variable whereas you are passing a string
CMD.Parameters("#date", SqlDbType.DateTime).value = TextBox1.Text

Commit button won't work when adding a record to Access Database

So I've been doing this personal project for myself where I'm trying to create a program where the user (me in this case) can add, delete, update a database via a form where I can fill out the necessary information.
To give a general idea, the main form has a data grid view where if I click load, the database appears wit the records. I got all of that set. However where I am having trouble is in Form1 which is the adding a record form where I write down the information and after filling it out I press the "commit" button so that it can write it on the MS Access Database. This is a general view of the code I have inside commit button. Just for reference, Profiles is the name of the mdb file and Contacts is the name of the table containing the recods.
Imports System.Data.OleDb
Private Sub btnCommit_Click(sender As Object, e As EventArgs) Handles btnCommit.Click
If inc <> 0 Then
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim dsnewrow As DataRow
dsnewrow = ds.Tables("Profiles").NewRow()
dsnewrow.Item("First_Name") = FirstNameText.Text
dsnewrow.Item("Last_Name") = LastNameText.Text
ds.Tables("Profiles").Rows.Add(dsnewrow)
da.Update(ds, "Profiles")
Main.DataGridView1.Refresh()
MsgBox("New Record added")
End If
End Sub
What I don't know is if it's necessary to add this following code to Form1_load:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source= path to the mdb file"
con.ConnectionString = dbProvider & dbSource
con.Open()
Sql = "SELECT * FROM Contacts"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Profiles")
con.Close()
Maxrows = ds.Tables("Profiles").Rows.Count
inc = -1
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
the following are declared, just for reference:
Dim con As New OleDb.OleDbConnection
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
Dim dbProvider, dbSource As String
Dim sql As String
Dim Maxrows As Integer
Syntax error in INSERT INTO statement on this line:da.Update(ds, "Profiles")
Any help would be greatly appreciated, been at it for days unfortunately :/
Let me know if you need any additional information to clarify.
Try this. In your btnCommit_Click method after
Dim cb As New OleDb.OleDbCommandBuilder(da)
add the following:
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
Does that help?