I'm trying to get data from a database but keep getting the following error.
Conversion failed when converting the varchar '102A' to data type int
The database table has 3 columns UserID
, UserName
, UserInfo
, all of them defined as type varchar
.
There is also a user in the table with ID 102A.
I'm trying to get the Username of the User with ID 10307.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim datareader As SqlDataReader
con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Database.mdf;Integrated Security=True;User Instance=True"
Try
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT * FROM Users WHERE UserID = 10307"
datareader = cmd.ExecuteReader
datareader.Read()
MsgBox(datareader.GetValue(2))
datareader.Close()
con.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
End Sub
I also tried to change datareader.GetValue
to datareader.GetString
but I get the same error.
Can anyone help me please, I've been stuck for days now...
Thank you
1条答案
按热度按时间vq8itlhq1#
I think, you have to use datatable. You can use that example: