InvalidCastExeption when trying to dim a string - sql

Im having a problem when trying to run my code. Im new to stackoverflow but will try to explain my problem.
Well, i get a "InvalidCastExeption" with the explanation
"Converson from string "Filename" to type "Integer" is not valid.
The confusing part is that FileName is a nvarchar(30) in my SQL database, and sName a string.
Look at the code, it failes at the dim sName = ...
Ps - I have tried to convert.toint / Cint, but it doesnt help. AND i want it as a string, not a integer!
Imports System
Imports System.Data
Imports System.Data.SqlClient
Public Class SelectrecipieDatabaseManager
Private Const CONNECTION_STRING As String = "Data Source=RYOW701;Initial Catalog=RyReci;Integrated Security=True"
Private connection As SqlConnection = Nothing
Private command As SqlCommand = Nothing
Public Sub RecipieHandler(ByVal Choice As String)
Dim reader As SqlDataReader
connection = New SqlConnection(CONNECTION_STRING)
Try
connection.Open()
Dim Query As String
Query = "select * from TbNew"
command = New SqlCommand(Query, connection)
reader = command.ExecuteReader
While reader.Read
Dim sName = reader.GetString("FileName")
RecipieForm.ComboBoxRec.Items.Add(sName)
End While
Catch ex As SqlException
MessageBox.Show(ex.Message)
Finally
connection.Close()
connection.Dispose()
End Try
End Sub
End Class

The getString method expects an ordinal number as it's parameter, not a string. Do this instead:
reader = command.ExecuteReader
Dim columnID As Integer = reader.GetOrdinal("FileName")
While reader.Read
Dim sName = reader.GetString(columnID)
RecipieForm.ComboBoxRec.Items.Add(sName)
End While

Related

Call a vb.net function stored in an access table

I stored some function's names in an Access table, an I would like to execute them in vb.net, I can't find the way to do it, maybe someone know how to do it.
public sub KeyDatesProcess()
Dim sqlQuery As String
Dim cmd As OleDbCommand
Dim rs As OleDbDataReader
Dim listForStartDates As List(Of CriticalDates)
Dim listForFinishDates As List(Of CriticalDates)
Try
sqlQuery = "select * from wbs_l2"
cmd = New OleDbCommand With {
.Connection = connection,
.CommandText = sqlQuery
}
rs = cmd.ExecuteReader()
Do While rs.Read
Debug.Print(rs(0) & " " & rs(3))
listForStartDates = CallByName(rs(6).ToString) 'this field contains a function
listForFinishDates = CallByName(rs(7).ToString) 'this field contains a function
Loop
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Need help figuring out why this sqlcommand EsecuteReader fails in .NET 4.5 and VS 2012 but not in .NET 3.5 and VS 2008

H,
This section of the code is failing
Current.Response.OutputStream.Write(CType(docRead("document"), Byte()), 0, 999999999)
I am trying to figure this out. The legacy VS 2008 code works fine but after converting to VS 2012 the code throws the error - The sum of offset and count is greater than the length of the buffer. Any and all help with this is appreciated.
Public Sub ViewDoc(ByVal docid As Integer)
Dim dbRead As SqlDataReader
Dim sqlConn As New SqlConnection
Dim docRead As SqlDataReader
Try
'Dim connStr As String = System.Configuration.ConfigurationSettings.AppSettings("sqlConnectionString")
'Dim sqlConn As SqlConnection = New SqlConnection(connStr)
sqlConn = utls.NewOpenConnection
Dim docinfosql As String = "SELECT Contenttype FROM VW_Rev_DocInfo WHERE DocInfoid = " & docid
Dim docsql As String = "select Document from vw_Documents WHERE DocInfoid = " & docid
Dim dbComn As SqlCommand = New SqlCommand(docinfosql, sqlConn)
Dim docComn As SqlCommand = New SqlCommand(docsql, sqlConn)
'sqlConn.Open()
dbRead = dbComn.ExecuteReader
Dim contenttype As String = ""
While dbRead.Read
contenttype = dbRead("Contenttype").ToString.Trim
End While
dbRead.Close()
docRead = docComn.ExecuteReader
Current.Response.Clear()
Current.Response.ContentType = contenttype
Current.Response.AppendHeader("content-disposition", "")
While docRead.Read
Current.Response.OutputStream.Write(CType(docRead("document"), Byte()), 0, 999999999)
End While
Current.Response.Flush()
Current.Response.End()
Catch Ex As Exception
'added exception method if Thread was being aborted exception is raised then response write is not available
If Not Ex.Message = "Thread was being aborted." Then
Throw
End If
Finally
If Not sqlConn Is Nothing Then
If Not sqlConn.State = ConnectionState.Closed Then
sqlConn.Close()
End If
End If
End Try
End Sub
As you (presumably) have access to the compiled code have you looked at the generated IL using any of the many free decompilers that are out there such as:
Just Decompile
DotPeek
IL Spy
etc.
See what the difference is and perhaps some project compat settings will help you here.

Error: Conversion from string to type Integer is not valid

I'm trying to run my code in sql but its keeps saying this message
"Conversion from string to type Integer is not valid"
Any advice?
MysqlConn = New SqlConnection
MysqlConn.ConnectionString =
"Data Source=SABAHALI-SHEIKH;Initial Catalog=md_1103763;Integrated Security=True"
Dim READER As SqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "select * from md_1103763.dbo.customer"
COMMAND = New SqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
While READER.Read
Dim fName = READER.GetString("firstname")
ComboBox1.Items.Add(fName)
End While
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
the source of your error is
Dim fName = READER.GetString("firstname")
GetString method takes int as parameter and not string. You are passing string to it. I would recommend that you use column index. the best way to do this is captured in Andrew Morton's comment
Please, remove the GetString().
So it would be this...
Dim fName = READER("firstname ")

How to extract data from Access db and place it into a text box using vb.net?

Hi guys I'm trying to search an employee information using SQL from MS Access, and hoping to put the fname lname and such details in their respective textbox which correspond to a specific employee's ID number. I have managed to make the SQL work but I don't know how to extract files from my sql statement and place it inside .text(text box), can you please guide me? Thanks
Here is my code so far:
(UPDATED my code) got an error message : Additional information: ExecuteReader: Connection property has not been initialized. Highlighting Reader below. How can i fix this? I'm trying to extract data and place it into the textbox? Thanks
Private Sub eNumText_SelectedIndexChanged(sender As Object, e As EventArgs) Handles eNumText.SelectedIndexChanged
Dim dbSource = "Data Source= C:\Databse\Company_db.accdb"
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
Dim sqlQuery As String
Dim sqlCommand As New OleDbCommand
Dim sqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
Dim empNum As String
Dim empFname As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
Dim empYears As String
empNum = eNumText.Text
empFname = empFnameText.Text
empLname = empLnameText.Text
empDept = DeptText.Text
empStat = StatText.Text
empYears = yearstext.Text
sqlQuery = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
With sqlCommand
.CommandText = sqlQuery
.Connection = con
.Parameters.AddWithValue("EmpID", empNum)
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(Table)
End With
With DataGridView1
.DataSource = Table
End With
End With
Dim path = "Data Source= C:\Databse\Company_db.accdb"
Dim command = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
QueryData(path, command)
con.Close()
End Sub
Private Sub QueryData(PathDb As String, command As String)
Using connection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathDb)
Using da As New System.Data.OleDb.OleDbCommand(command, connection)
connection.Open()
Dim reader = da.ExecuteReader()
If reader.Read() Then
empFnameText.Text = reader("fname")
empLnameText.Text = reader("lname")
End If
connection.Close()
End Using
End Using
End Sub
for this, you need only this classes: Connection, Command, Reader.
Other classes in the code in question, some are redundant and some are required but in complicated than a simple case presentation.
Private Sub QueryData(PathDb As String, command As String)
Using connection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathDb)
Using com As New System.Data.OleDb.OleDbCommand(command, connection)
connection.Open()
Dim reader = com.ExecuteReader()
If reader.Read() Then
TextBox1.text = reader("fname")
TextBox2.text = reader("lname")
End If
connection.Close()
End Using
End Using
End Sub
call the method so:
Dim path = "C:\Databse\Company_db.accdb"
Dim command = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
QueryData(path, command)
EDIT - Use parameters:
Private Sub QueryData(PathDb As String, command As String, id As String)
Using connection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathDb)
Using com As New System.Data.OleDb.OleDbCommand(command, connection)
com.Parameters.AddWithValue("", id)
connection.Open()
Using reader = com.ExecuteReader()
If reader.Read() Then
TextBox1.Text = reader("fname")
TextBox2.Text = reader("lname")
End If
End Using
connection.Close()
End Using
End Using
End Sub
Call the method:
Dim path = "C:\Databse\Company_db.accdb"
Dim command = "SELECT * FROM tbl_empinfo WHERE EmpID = ?"
Dim empNum = "..."
QueryData(path, command, empNum)

VB.NET connection to MS Access

I get an error when I am trying to connect to a Microsoft Access DB using VB.NET. I see examples all over the web. My code looks like those examples, however I am getting a build error message stating:
Type 'System.Data.OleDb.OleDbConnection' is not defined.
I have tried adding some kind of import statement for the system.data.oledb... but that does not seem to work. My code is below. It is a basic connection so I am thinking that I am missing some kind of add in, library, or setting. Any and all help would be greatly appreciated.
Public Function TestMain(ByVal args() As Object) As Object
' Connection String to MS Access DB
Dim connectStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Users\DMalerman\keyword.accdb;" & _
"Persist Security Info=False;"
MsgBox(connectStr)
' Create connection to the db
Using connection As New System.Data.OleDb.OleDbConnection(connectStr)
' Create the SQL Query
Dim readQuery As String = "Select KeywordDriver.ScriptName from KeywordDriver " & _
"where KeywordDriver.Keyword = test"
Dim queryCommand As New System.Data.OleDb.OleDbCommand(readQuery, connection)
'Open the Connection
connection.Open()
' Query the Database
Dim dbReader As System.Data.OleDb.OleDbDataReader = queryCommand.ExecuteReader()
' Loop until there is nothing left to read
While dbReader.Read()
Dim sKeyword As String = ""
sKeyword = dbReader.GetString(0)
MsgBox(sKeyword)
End While
' Close the Reader
dbReader.Close()
End Using
Return Nothing
End Function
did you try
imports System.Data.OleDb
?
if so, did it give you an error?
Please try to modify this line:
Dim queryCommand As New System.Data.OleDb.OleDbCommand(readQuery, connection)
by putting these only:
Dim queryCommand As New System.Data.OleDb.OleDbCommand(readQuery)
queryCommand.Connection = connection
Imports System.Data
Imports System.Data.OleDb
Module Module1
Public str As String
Public con As OleDbConnection
Public cmd As OleDbCommand
Public dtreader As OleDbDataReader
Public dtadapter As OleDbDataAdapter
Public Sub openconn()
str = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database2.mdb"
con = New OleDbConnection(str)
Try
con.Open()
Catch ex As Exception
MessageBox.Show("gagal koneksi")
End Try
End Sub
End Module