Crystal report error message - vb.net

ive been dealing with a kind of no error message my application is throwing after the setup has been installed on my machine.
The application run fine and generate a report exactly the way i want it. The problem is that after compiling it as set up, it throw this message:
System.Runtime.InteropServices.COMException (0x80000000);
No error.
at
CrystalDesisionsReportAppServer.Controllers.DatabaseControllerClass.ReplaceConnection(Object oldConnection, Object newConnection, Object parameterFields, Object crDBOptionUseDefault)
at
CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSourceInternal(Object val, Type type)
at
CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSource(DataSet dataSet)
at Presby_Soft.reportFrm.reportFrm_Load(Object sender, EventArgs e)
this is the code im using:
Private Sub reportFrm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Try
Dim rpt As New CrystalReport1()
Dim da As New SQLiteDataAdapter
Dim ds As New presbydbDataSet
'Dim cmd As New SQLiteCommand("SELECT personal_details.fn, training.training_level FROM personal_details INNER JOIN training ON personal_details.Staff_ID ='" + detailsFrm.Label13.Text + "'", conn)
Dim cmd As New SQLiteCommand("SELECT * FROM personal_details WHERE personal_details.staff_ID='" + detailsFrm.Label13.Text + "'", conn)
cmd.ExecuteNonQuery()
da.SelectCommand = cmd
da.Fill(ds, "personal_details")
rpt.Subreports.Item("persoRpt").SetDataSource(ds)
CrystalReportViewer1.ReportSource = rpt
Catch ex As Exception
MsgBox(ex.ToString)
End Try
conn.Close()
End Sub
Please help, I really don't know how to go about this problem. Thanks for answering

Well I managed to get rid of this problem. The issue is that i was adding the business object files directly into the bin folder while the business object is already installed on the computer. I just removed the business object files i added and the application worked fine.

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)"

Set up load event on windows form tab

I am currently working in vb.net with windows form applications. I am using a multi-tab windows form where I want a data grid view to be loaded with information from an sql table as soon as the form opens. However, I can not find an event that uses the load feature coupled with the tab. Is there a way to hard code this?
...
Private Sub DataGridView1_CellContentClick_1(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridLine2.CellContentClick
Try
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As SqlCommand = New SqlCommand("Select * FROM Production.dbo.tblOrdered", conn1)
Dim da As New SqlDataAdapter
da.SelectCommand = comm1
da.Fill(dt)
'select customerName as customer, contactname as contact person
'from cusomters;
End Using
conn1.Close()
End Using
DataGridLine2.DataSource = dt
Catch ex As Exception
MsgBox("Unable to make SQL Connection, please contact an engineer!")
MsgBox(ex.ToString)
End Try
End Sub
End Class

Subroutine not firing

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.