Subroutine not firing - vb.net

I have the following subroutines:
Private Sub Exceptionquery()
Dim connection As System.Data.SqlClient.SqlConnection
Dim connectionString As String = "Initial Catalog=mdr;Data Source=xxxxx;uid=xxxxx;password=xxxxx"
Dim _sql As String = "SELECT [Exceptions].Employeenumber,[Exceptions].exceptiondate, [Exceptions].starttime, [exceptions].endtime, [Exceptions].code, datediff(minute, starttime, endtime) as duration INTO scratchpad3 " + _
"FROM [Exceptions]" + _
"where [Exceptions].exceptiondate between #payperiodstartdate and payperiodenddate" + _
"GROUP BY [Exceptions].Employeenumber, [Exceptions].Exceptiondate, [Exceptions].starttime, [exceptions].endtime," + _
"[Exceptions].code, [Exceptions].exceptiondate"
connection = New SqlConnection(connectionString)
connection.Open()
Dim _CMD As SqlCommand = New SqlCommand(_sql, connection)
_CMD.Parameters.AddWithValue("#payperiodstartdate", payperiodstartdate)
_CMD.Parameters.AddWithValue("#payperiodenddate", payperiodenddate)
connection.Close()
End Sub
Public Sub exceptionsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exceptionsButton.Click
Exceptionquery()
Dim connection As System.Data.SqlClient.SqlConnection
Dim adapter As System.Data.SqlClient.SqlDataAdapter = New System.Data.SqlClient.SqlDataAdapter
Dim connectionString As String = "Initial Catalog=mdr;Data Source=xxxxx;uid=xxxxx;password=xxxxx"
Dim ds As New DataSet
Dim _sql As String = "SELECT * from scratchpad3"
connection = New SqlConnection(connectionString)
connection.Open()
Dim _CMD As SqlCommand = New SqlCommand(_sql, connection)
_CMD.Parameters.AddWithValue("#payperiodstartdate", payperiodstartdate)
_CMD.Parameters.AddWithValue("#payperiodenddate", payperiodenddate)
adapter.SelectCommand = _CMD
Try
adapter.Fill(ds)
If ds Is Nothing OrElse ds.Tables.Count = 0 OrElse ds.Tables(0).Rows.Count = 0 Then
'it's empty
MessageBox.Show("There was no data for this time period. Press Ok to continue", "No Data")
connection.Close()
Exceptions.saveButton.Enabled = False
Exceptions.Show()
Else
connection.Close()
Exceptions.Show()
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
connection.Close()
End Try
End Sub
and when I press the button:
Public Sub exceptionsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exceptionsButton.Click
My subroutine Exceptionquery is not being fired. I know that it's probably something simple that I'm overlooking but don't know what it is. Can someone please assist me with this?
Thank you

Are you sure ExceptionQuery() is being run from exceptionsButton_Click? Your example as shown should work. Step through with the debugger and verify that your button event is actually firing.

it should work, check if the event handler exceptionsButton_Click is called at all and see with a breakpoint if the execution gets into it.
P.S. a small very important detail: the way you are handling the connection is not optimal, you can use a using block, something like this:
using (dim connection as New SqlConnection(connectionString)
...
in this way you are sure connection is closed and disposed when running out of scope and you do not need all those connection.close in the if/else and catch which are wrong anyway the way you did it so far, because if the connection has been closed and you enter the catch and try to close it again, there will be another error.

Related

Connection string problem connecting to local SQL database using VB.NET in Visual Studio

I can't understand why I can't connect with my SQL Server Express LocalDB. I keep getting in to trouble with my connection string. This is what I have tried:
Imports System.Data.OleDb
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim conString As String 'Connection string
Dim con As OleDbConnection 'Connecting to your database
Dim Command As OleDbCommand 'Query "What do you want in the database"
'conString = "PROVIDER=System.Data.SqlClient v4.0; Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DatabaseInnlogging.mdf;Integrated Security=True"
'conString = "PROVIDER=SQLOLEDB; Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DatabaseInnlogging.mdf;Integrated Security=True"
'conString = "PROVIDER=System.Data.SqlClient; Data Source=C:\Users\Bruker\source\repos\InnloggingFørsøkv1\InnloggingFørsøkv1\DatabaseInnlogging.mdf;Integrated Security=True"
'conString = "PROVIDER=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\Bruker\source\repos\InnloggingFørsøkv1\InnloggingFørsøkv1\DatabaseInnlogging.mdf;Integrated Security=True"
'conString = "PROVIDER=System.Data.SqlClient v4.0; Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DatabaseInnlogging.mdf;Integrated Security=True"
Try
con = New OleDbConnection(conString)
con.Open()
Command = New OleDbCommand("select * from LogInTable where UserID = ? and Password = ?", con)
Dim parm1 As OleDbParameter, parm2 As OleDbParameter
parm1 = Command.Parameters.Add("#UserID", OleDbType.VarChar)
parm2 = Command.Parameters.Add("#Password", OleDbType.VarChar)
parm1.Direction = ParameterDirection.Input
parm2.Direction = ParameterDirection.Input
parm1.Value = Me.TextBox1.Text
parm2.Value = Me.TextBox2.Text
Command.Connection.Open()
Dim reader As OleDbDataReader
If reader.Read = True Then
Me.DialogResult = DialogResult.OK
Else
MsgBox("Invalid UserID or Password")
End If
reader = Command.ExecuteReader
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
I have tried several connection strings, but none is working.
But with the number 4, I got error
Multiple-step OLE DB operation generated errors.check each OLE DB status value
The others results in an error:
provider not recognized
My other attempt was with SqlClient:
Imports System.Data.SqlClient
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myConn As SqlConnection
myConn = New SqlConnection("Initial Catalog=OutComes; Data Source=localhost;Integrated Security=SSPI;")
'"Data Source = (LocalDB) \ MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DatabaseInnlogging.mdf;Integrated Security=True")
' "Data Source=localhost;Integrated Security=SSPI;")
'Create a Command object.
Dim myCmd As SqlCommand
myCmd = myConn.CreateCommand
myCmd.CommandText = "SELECT UserID, Password FROM LogInTable"
'Open the connection.
myConn.Open()
Dim results As String
Dim myReader As SqlDataReader
myReader = myCmd.ExecuteReader()
'Traverse the DataSet and Display in GUi for Example:
Do While myReader.Read()
results = results & myReader.GetString(0) & vbTab &
myReader.GetString(1) & vbLf
Loop
'Display results.
MsgBox(results)
' Close the reader and the database connection.
myReader.Close()
myConn.Close()
End Sub
My error here was:
System.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while connecting to SQL Server. The server was not found or was not available. Verify that the instance name is correct and that SQL Server is configured to accept external connections. (provider: Named Pipes Provider, error: 40 - Unable to open a connection to SQL Server)
I have one table in my SQL Server database with two columns UserID and password.
I would be very grateful if someone could point me in the right direction here. I have read many post on the subject but cant seem to find where I go wrong. My main goal here is to connect with my database.
As you are new you can try some visual tools it can help you to see more clear, I suggest you to try this approach, it's a half way to your solution :
In your visual Studio :
Menu Tools
Connection to database
In the Dialog
Data Source : Microsoft SQL Server (sqlClient)
Server Name : ****
you should find your server here, select it, Else that's mean you have problem with your server installation
Authentification : Windows Authentification
as i see in your example your are not using SQL id so that's fine
Connection to database:
Select the Database that you already created, if nothing seen
that's mean you didn't created or you don't have rights to access
Then Click in button Test Connection
if success then click OK
Then go to your ToolBox
Data
DataGridView drop it in your form
select data source : in bottom you will see + Add the data source
click on it
You will have a Dialog, choose Database -> Dataset ->
choose you data connection
you should see a line in the combobox with your server name \ your Database.dbo
Check in the checkbox "Show the connection string saved in the application"
you will see clearly your connection string
Next -> Next > check Tables
Finish
If you stuck in some part let me know to clarify you by an Edit
First of all, THANK YOU :), I got it to work. But I still have som questions.
I started with a fresh project and made a local sqlDB with one table
with two columbs "UserID" and "Password".
I had one line in this table with "Admin" and "pass"
I did not use the table designer or add a datasource.
I followed your description to the letter and copied my connectionstring under tool connect...
That worked fine and I found the mdf file and was able to connect to it
Loaded the form with a datagrid and bound it to the datasource. It worked properly
Then I tried to connect to the DB under a new button manualy. I got this error message:
System.Data.SqlClient.SqlException:
'Cannot attach file 'C:\Users\Bruker\source\repos\Connect_v2\Connect_v2\bin\Debug\Database1.mdf'
as database 'OutComes
' because this file is already in use for database
'C:\USERS\BRUKER\SOURCE\REPOS\CONNECT_V2\CONNECT_V2\BIN\DEBUG\DATABASE1.MDF''
This was the class:
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Database1DataSet.LogInTable' table. You can move, or remove it, as needed.
Me.LogInTableTableAdapter.Fill(Me.Database1DataSet.LogInTable)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myConn As SqlConnection
myConn = New SqlConnection("Initial Catalog=OutComes; Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;Connect Timeout=30")
'Create a Command object.
Dim myCmd As SqlCommand
myCmd = myConn.CreateCommand
myCmd.CommandText = "SELECT UserID, Password FROM LogInTable"
'Open the connection.
myConn.Open()
Dim results As String
Dim myReader As SqlDataReader
myReader = myCmd.ExecuteReader()
'Traverse the DataSet and Display in GUi for Example:
Do While myReader.Read()
results = results & myReader.GetString(0) & vbTab &
myReader.GetString(1) & vbLf
Loop
'Display results.
MsgBox(results)
' Close the reader and the database connection.
myReader.Close()
myConn.Close()
End Sub
I tried to comment out the load event and It connected with the DB manualy. It worked :)
Imports System.Data.SqlClient
Public Class Form1
'Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' 'TODO: This line of code loads data into the 'Database1DataSet.LogInTable' table. You can move, or remove it, as needed.
' Me.LogInTableTableAdapter.Fill(Me.Database1DataSet.LogInTable)
'End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myConn As SqlConnection
myConn = New SqlConnection("Initial Catalog=OutComes; Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;Connect Timeout=30")
'Create a Command object.
Dim myCmd As SqlCommand
myCmd = myConn.CreateCommand
myCmd.CommandText = "SELECT UserID, Password FROM LogInTable"
'Open the connection.
myConn.Open()
Dim results As String
Dim myReader As SqlDataReader
myReader = myCmd.ExecuteReader()
'Traverse the DataSet and Display in GUi for Example:
Do While myReader.Read()
results = results & myReader.GetString(0) & vbTab &
myReader.GetString(1) & vbLf
Loop
'Display results.
MsgBox(results)
' Close the reader and the database connection.
myReader.Close()
myConn.Close()
End Sub
End Class
This is great but I still wonder why I got the error message. Is it because the datagridview tableadapter holds a constanctly open connection to the DB. And is not possible to have multiple open connections at the same time ?

Visual Basic 2017 - DataGridView

So I am having difficulty with my sub routines. I am creating an app to help with dungeon masters. Part of what my application will do is display several spreadsheets, in separate tabs, containing a list of items and details related to them. I want to reuse several my code instead of writing 20 or so nearly identical sub routines.
Here is my code, I am not sure how to solve my problem.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
loadExcel("C:\Users\secretUserName\source\repos\QUILLandDAGGER\QUILLandDAGGER\bin\Debug\recIntKnowl.xls",dgvRecEntKnowl)
End Sub
Private Sub loadExcel(strFilename As String, dgvView As DataGridView)
Try
Dim MyConnection As OleDb.OleDbConnection
Dim Ds As System.Data.DataSet
Dim MyAdapter As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='strFileName';Extended Properties=Excel 8.0;")
MyAdapter = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
Ds = New System.Data.DataSet
MyAdapter.Fill(Ds)
dgvView.DataSource = Ds.Tables(0)
MyConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Build the method like this:
Private Function LoadExcel(ByVal strFilename As String, Optional ByVal SheetName As String = "Sheet1$") As DataTable
Dim SQL As String = "SELECT * FROM [" & SheetName & "]"
Dim result As New DataTable
Using MyConnection As New OleDb.OleDbConnection(), _
MyCommand As New OleDb.OleDbCommand(SQL, MyConnection)
MyConnection.Open()
Using reader As OleDb.OleDbDataReader = MyCommand.ExecuteReader()
result.Load(reader)
End Using
End Using
Return result
End Function
There are numerous improvements in this new code, both great and small. The most important are adding Using blocks, separating the data access from the UI, and designing functions that accept input in order to return a result.
Call it like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
dgvRecEntKnowl.DataSource = LoadExcel("C:\Users\secretUserName\source\repos\QUILLandDAGGER\QUILLandDAGGER\bin\Debug\recIntKnowl.xls.xls")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
As to whether this will actually fix anything... that depends on the problem you're having, which wasn't included in the posted question.
Sorry for failing to post my problem. I actually didn't know directly where my problem was and I've spent hours trying to find that.
My first problem was passing the string that contains directly to the file. It's poorly pointing to the file, which I'll resolve and have it point to a sub directory at a later point.
My second problem was with a specific line and I resolved that.
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='C:\Users\seidl\source\repos\QUILLandDAGGER\QUILLandDAGGER\bin\Debug\detect.xls';Extended Properties=Excel 8.0;")
This line of code was my original text and it worked.
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='strFileName';Extended Properties=Excel 8.0;")
Was what I tried and it didn't work. I even removed the ' that surrounded the text and it didn't work.
So it finally clicked with me, to try something I used in Java when writing strings of texts and I needed variables in my lines of text. +
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + strFileName + "';Extended Properties=Excel 8.0;")
This ended up working like a charm. I am guessing that OleDbConnection takes in a long string of characters and breaks down the string to read in what is needed. I could be wrong but this is incredibly interesting! It only took a many hours to finally see this.
Joel, I will investigate what you replied with and try and clean up my code. Thank you!

VB.Net - Inserting data to Access Database using OleDb

Can you please tell me what's wrong with the code I'm using? Everytime I execute this, it throws the exception (Failed to connect to database)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim conn As New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\socnet.accdb"
Dim sql As String = String.Format("INSERT INTO login VALUES('{username}','{password}','{secques}','{secans}')", txt_username.Text, txt_passwd.Text, txt_secquestion.Text, txt_secansw.Text)
Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
'Open Database Connection
sqlCom.Connection = conn
conn.Open()
Dim icount As Integer = sqlCom.ExecuteNonQuery
MessageBox.Show(icount)
MessageBox.Show("Successfully registered..", "Success", MessageBoxButtons.OK, MessageBoxIcon.Error)
Catch ex As Exception
MessageBox.Show("Failed to connect to Database..", "Database Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
cmd_submit2_Click(sender, e)
End If
End Sub
I am using Access 2013 and VS 2015 Community, if that helps. Thank you.
You should use a parameterized approach to your commands.
A parameterized query removes the possibility of Sql Injection and you will not get errors if your string values are not correctly formatted.
Note that if you don't do anything in the exception block then it is better to remove it and let the exception show itself or at least show the Exception.Message value, so you are informed of the actual error.
Finally every disposable object should be created with the Using statement that ensures a proper close and dispose of such objects (in particular the OleDbConnection)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sql As String = "INSERT INTO login VALUES(#name, #pass, #sec, #sw)"
Using conn = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\socnet.accdb")
Using sqlCom = New System.Data.OleDb.OleDbCommand(sql, conn)
conn.Open()
sqlCom.Parameters.Add("#name", OleDbType.VarWChar).Value = txt_username.Text
sqlCom.Parameters.Add("#pass", OleDbType.VarWChar).Value = txt_passwd.Text
sqlCom.Parameters.Add("#sec", OleDbType.VarWChar).Value = txt_secquestion.Text
sqlCom.Parameters.Add("#sw", OleDbType.VarWChar).Value = txt_secansw.Text
Dim icount As Integer = sqlCom.ExecuteNonQuery
End Using
End Using
End Sub
Keep in mind that omitting the field names in the INSERT INTO statement requires that you provide values for every field present in the login table and in the exact order expected by the table (So it is better to insert the field names)
For example, if your table has only the 4 known fields:
Dim sql As String = "INSERT INTO login (username, userpass, secfield, secfieldsw) " & _
"VALUES(#name, #pass, #sec, #sw)"

Close connection if there is an error 'connection not closed'?

My vb.net application shows an error.
Connection not closed. Connection's current state is open
Here is my code. Please help me rectify the error:
Private Sub saveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles saveBtn.Click
addSubject()
End Sub
Private Function addSubject() As Boolean
Dim cmd As New SqlCommand
Dim ok As Boolean = False
cmd.Connection = con
cmd.CommandText = " INSERT INTO Subjects(subject_name) VALUES(#inn)"
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("inn", subjectTxt.Text)
Try
con.Open()
cmd.ExecuteNonQuery()
ok = True
Catch ex As Exception
MessageBox.Show(ex.Message, "Add failed")
ok = False
End Try
cmd.Dispose()
con.Close()
Return ok
con.Close()
End Function
There might be an open connection in your previous codes in which you were not able to close it.
This connection state checker could help you:
If connection.State <> 1
connection.Open()
End IF
wrap sqlcommand in a using statement. Don't call close or dispose manually.
Try to check connection state before opening, no need to open connection if it has already opened :
If con.State <> ConnectionState.Open Then
con.Open()
End If
That will help you avoid current exception.
Anyway, root cause of this problem could be somewhere else. Because, your code already tried to close connection in the end, so it seems that there is another part of your program that is not closing the connection properly.
Possible solution is not to share your connection object, instantiate new connection every time needed and wrap it around using statement as also pointed by #DeveloperGuo.

how to change selected option of textbox based on datareader result vb

.hi everyone I have this code:
Private Sub EditPage_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'InventorySysDataSet.tb_master_products' table. You can move, or remove it, as needed.
Me.Tb_master_productsTableAdapter.Fill(Me.InventorySysDataSet.tb_master_products)
sqlCnn = New SqlConnection("Data Source=ZEREY\SQLEXPRESS2008;Initial Catalog=InventorySys;Integrated Security=SSPI")
Me.txtRowId.Text = Form1.txtRowId.Text
'MsgBox(Me.txtRowId.Text)
sql = "Select * from tb_master_inventory_per_day where Inventory_Date = " & txtRowId.Text & ""
Dim upcmd As New SqlCommand("Select * from tb_master_inventory_per_day where Row_Id = #Row_Id", sqlCnn)
upcmd.Parameters.Add(New SqlParameter("#Row_Id", Me.txtRowId.Text))
upcmd.Connection.Open()
Try
Dim dr As SqlDataReader = upcmd.ExecuteReader()
If dr.Read Then
txtInventoryDate.Text = dr.Item("Inventory_Date")
cboProductCode.DisplayMember = dr.Item("Product_Code")
txtQty.Text = dr.Item("Product_Count")
Else
MessageBox.Show("Error!")
End If
Catch ex As SqlException
If ex.Number <> 0 Then
'ErrorProvider1.SetError(Me.txtuseridprofile, "Login Id: " &
'Me.txtuseridprofile.Text & " :Not Found!")
upcmd.Connection.Close()
Exit Sub
End If
End Try
upcmd.Connection.Close()
End Sub
what i want to do is to automatically change the selected option of the cboProductCode on page load depending on the result of a query executed onload also.
help pls! TIA!
.Haha! it's funny that i have tried so many ways but not tried using cboProductCode.Text instead of cboProductCode.DisplayMember. It now works! :D