InvalidCastException saying that "Specified cast is not valid." - vb.net

Hi I got an InvalidCastException saying that "Specified cast is not valid.". I dont know where is the problem. Does my code has an error?
This is my code:
Private Sub Form5_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\patientinfo.accdb"
Conn.Open()
'====retrieve values in database=============
Dim statement As String = " SELECT patient_name,patient_age,date_confinement,type_sickness, type_fluid, bottle_used, drop_rate FROM tblPatientInfo WHERE 1 ORDER BY ID "
RetrieveInfos(statement)
End Sub
Public Sub RetrieveInfos(ByRef statement As String)
Dim cmd As OleDbCommand = New OleDbCommand
With cmd
.CommandText = statement
.CommandType = CommandType.Text
.Connection = Conn
.ExecuteNonQuery()
'--read records in access database----------------
Dim reader As OleDbDataReader = cmd.ExecuteReader
If reader.Read Then
lblName.Text = reader.GetString(0)
lblAge.Text = reader.GetString(1)
lblDate.Text = reader.GetString(2)
lblSickness.Text = reader.GetString(3)
lblFluid.Text = reader.GetString(4)
lblBottle.Text = reader.GetString(5)
lbldrops.Text = reader.GetString(6)
reader.Close()
End If
End With
End Sub
Any help would be appreciated. Thanks! :3

A very annoying part of VB working with datatypes is that some of them cause it to have a huge flap if they're empty. Best way around is to convert the ready to either an empty value or the default null value for the data type. Try the following:
lblName.Text = If(reader.isdbnull(0),Nothing,reader.GetString(0))
lblAge.Text = If(reader.isdbnull(1), 0, reader.GetInt16(1))
lblDate.Text = If(reader.isdbnull(2), date.minvalue, reader.Getdatetime(2)
lblSickness.Text = If(reader.isdbnull(3), Nothing, reader.GetString(3)
lblFluid.Text = If(reader.isdbnull(4), Nothing, reader.GetString(4))
lblBottle.Text = If(reader.isdbnull(5), Nothing, reader.GetString(5))
lbldrops.Text = If(reader.isdbnull(6), Nothing, reader.GetString(6))

Based on your comment to the question, I would suggest changing
lblAge.Text = reader.GetString(1)
to
lblAge.Text = reader.GetInt32(1).ToString
Also, make sure you use the appropriate Get for each column. For a Date you should use GetDateTime(). Here is a link to the MSDN for OleDbDataReader; the left side will have a list of all the methods that you can use for reference.

Try checking if the value is null:
If TypeOf reader(1) Is DBNull Then
lblAge.Text = reader.GetString(1)
End If
But that will only work if it's a string. If it's not a string, this should work with any data type:
If TypeOf reader(1) Is DBNull Then
lblAge.Text = reader(1).ToString()
End If

Related

a beginner in vb.net.. working on a login form

Imports MySql.Data.MySqlClient
Public Class Form1
Dim cmd As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim con As MySqlConnection = JOKENCONN()
Public Function JOKENCONN() As MySqlConnection
Return New MySqlConnection("server=localhost; user id=root; password=; database =studentdb")
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GroupBox1.Enabled = False
End Sub
Private Sub LBLLOGIN_CLICK(sender As Object, e As EventArgs) Handles lbllogin.Click
lbllogin.Text = "Login"
lbllogin.Text = "Login"
lblname.Text = "Hi, Guest"
If lbllogin.Text = "Login" Then
GroupBox1.Enabled = True
End If
End Sub
Private Sub BTNOK_CLICK(sender As Object, e As EventArgs) Handles btnok.Click
Dim Sql As String
Dim publictable As New DataTable
Try
If txtusername.Text = "" And txtpass.Text = "" Then
MsgBox("Password or username is incorrect!")
Else
Sql = "select ' from tbluseraccount where username='" & txtusername.Text & "' and userpassword='" & txtpass.Text & "'"
With cmd
.Connection = con
End With
da.SelectCommand = cmd
da.Fill(publictable)
If publictable.Rows.Count > 0 Then
Dim user_type As String
user_type = publictable.Rows(0).Item(4)
Name = publictable.Rows(0).Item(1)
If user_type = "Admin" Then
MsgBox("Welcome " & Name & "you login as Administrator")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
ElseIf user_type = "cetakoradi2" Then
MsgBox("Welcome " & Name & "you login as cetakoradi2")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
Else
End If
Else
MsgBox("contact administrator to register")
txtusername.Text = ""
txtpass.Text = ""
End If
da.Dispose()
End If
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
End Class
this the error i received
ExecuteReader CommandText property has not been properly initialized
i really need help on that. this is the error that i receives. thank you
Assuming that the name of the field represented in publictable.Rows(0).Item(4) is named user_type, then you could use the following:
'Declare the object that will be returned from the command
Dim user_type As String
'Declare the connection object
Dim con As OleDbConnection
'Wrap code in Try/Catch
Try
'Set the connection object to a new instance
con = JOKENCONN()
'Create a new instance of the command object
Using cmd As OleDbCommand = New OleDbCommand("SELECT user_type FROM tbluseraccount WHERE username=#0 AND userpassword=#1;", con)
'Paramterize the query
cmd.Parameters.AddWithValue("#0", txtusername.Text)
cmd.Parameters.AddWithValue("#1", txtpass.Text)
'Open the connection
con.Open()
'Use ExecuteScalar to return a single value
user_type = cmd.ExecuteScalar()
'Close the connection
con.Close()
End Using
Catch ex As Exception
'Display the error
Console.WriteLine(ex.Message)
Finally
'Check if the connection object was initialized
If con IsNot Nothing Then
If con.State = ConnectionState.Open Then
'Close the connection if it was left open(exception thrown)
con.Close()
End If
'Dispose of the connection object
con.Dispose()
End If
End Try
If (String.IsNullOrWhitespace(user_type)) Then
'Failed login
ElseIf (user_type = "Admin") Then
'Admin login
ElseIf (user_type = "cetakoradi2") Then
'cetakoradi2 login
Else
'Not a failed login, but also not an admin or cetakoradi2 either
End If
What this code does is setup a parameterized query to get just the user_type where the username and password match the parameterized values. Since there should only ever be one record that matches those conditions (presumably) then we're able to use ExecuteScalar to return just that single field value.
Just to reinforce the point, MySqlCommand.ExecuteScalar, just like the Microsoft counterparts, "executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored" and returns " The first column of the first row in the result set, or a null reference if the result set is empty ".
The proposed code by #David checks for this condition using IsNullOrWhitespace.
ExecuteScalar is effective but retrieves only one value at a time.
The other option pursued by the OP is to return a datarow, which is a valid approach if he wants to return several fields at the same time. In his example he retrieves two fields for variables user_type and Name respectively.
Be careful, VB.net like any other programming language has reserved keywords. If you do not take a habit of using good naming conventions you might one day stumble upon on one of those keywords, possibly hit obscure bugs. Name is not a good name for a variable and has the potential for confusion since every object has a name property.
To address the specific issue at hand, the error message ExecuteReader CommandText property has not been properly initialized is self-explanatory. What should have been done is simply:
With cmd
.Connection = con
.CommandText = Sql
End With
You defined a command, but did not tell it what to do. In your code variable Sql is defined but unused. With this missing bit there is a chance the code will work as expected.
Small details:
Not critical, but his condition does not work if you enter whitespace for example:
If txtusername.Text = "" And txtpass.Text = "" Then
An improvement is to simply trim the values from the textboxes:
If txtusername.Text.Trim = "" And txtpass.Text.Trim = "" Then
But I think what you want is not an And but Or. I don't think you want to allow logins without passwords.
Instead of doing multiple If/ElseIf you could have a Select Case

how to display data in text box in vb.net using sql

Private Sub BtnReturn_Click(sender As Object, e As EventArgs) Handles btnReturn.Click
If BorrowAccession.Text = "" Or txtBorrowerstype.Text = "" Then
MsgBox("All fields are required.", MsgBoxStyle.Exclamation)
ElseIf txtremarks.Text = "Over Due" Then
sql = "Select * From `maintenance` fine ='" & txtfine.Text & "' "
reloadtxt(sql)
End sub
how will i display the fine in txtfine.text from my maintenance database after it satisfy the condition from txtremarks. i tried some youtube tutorials but only displaying it from data grid .. want i basically want is directly display it from database to textbox. btw im newbie in vb programming thank you in advance
for my reloadtxt this is the code.
Public Sub reloadtxt(ByVal sql As String)
Try
con.Open()
With cmd
.Connection = con
.CommandText = sql
End With
dt = New DataTable
da = New MySqlDataAdapter(sql, con)
da.Fill(dt)
Catch ex As Exception
' MsgBox(ex.Message & "reloadtxt")
Finally
con.Close()
da.Dispose()
End Try
End Sub
To populate an object with data from a database you need to access the objects text property.
Textbox1.Text = "Some Text, static or dynamic"
Since you are pulling the data from a datatable you would access the column named "fine" and put that value in the textbox.text property.
Textbox1.Text = dt.row(0).item("fine").tostring
Changed Or to OrElse because it short circuits the If and doesn't have to check the second condition if the first condition is True.
In the reloadtxt method you filled a DataTable and did nothing with it. I changed it to a Function that returns the DataTable. The connection and command are now included in a Using...End Using block so they are closed and disposed even if there is an error.
Never concatenate strings to build an sql statement. Always used parameters.
Private Sub BtnReturn_Click(sender As Object, e As EventArgs) Handles btnReturn.Click
If BorrowAccession.Text = "" OrElse txtBorrowerstype.Text = "" Then
MsgBox("All fields are required.", MsgBoxStyle.Exclamation)
ElseIf txtremarks.Text = "Over Due" Then
Dim dt = reloadtxt()
DataGridView1.DataSource = dt
End If
End Sub
Public Function reloadtxt() As DataTable
Dim dt As New DataTable
Using con As New MySqlConnection("Your connection string"),
cmd As New MySqlCommand("Select * From maintenance Where fine = #Fine", con)
cmd.Parameters.Add(#Fine, MySqlDbType.VarChar, 50).Value = txtfine.Text
Try
con.Open()
dt.Load(cmd.ExecuteReader)
Catch ex As Exception
MsgBox(ex.Message & "reloadtxt")
End Try
End Using
Return dt
End Function

How do i make padleft work with the below code. I want to do search with out leading zero

With the below code I can pull info with zero in the front. I am trying to eliminate entering zero for instance 789136 for 0789136. Please advise
Private Sub BtnSearch_Click(sender As System.Object, e As System.EventArgs) Handles BtnSearch.Click
Dim connection As New SqlConnection("DATABASE CONNECTION")
Dim Table As New DataSet
Dim ZeroFill As String
If TxtBoxW1.Text = "" Then
ZeroFill = TxtBoxW1.Text.Trim
ZeroFill = ZeroFill.PadLeft(4, "0")
MsgBox(" Please Enter a valid number", MessageBoxButtons.OK)
TxtBoxW1.Focus()
connection.Open()
Else
adapter = New SqlDataAdapter("Select * From TABLENAME where COLNAME = '" & TxtBoxW1.Text.Trim & "'", connection)
Command = New SqlCommandBuilder(adapter)
ds1 = New DataSet()
adapter.Fill(ds1, "TABLENAME")
DataGridView1.DataSource = ds1.Tables("TABLENAME")
End If
connection.Close()
End Sub
your code does not make sense in many was. I'm not even sure what do you really need with those leading zeros.
1) Removing leading zeros
Dim Value As String = "0789136"
Dim ValueWithoutLeadingZeros As String = Value.TrimStart("0"c)
2) Other incinsistencies
Your if statement tests for empty string in TxtBoxW1. So there's no reason to read this
ZeroFill = TxtBoxW1.Text.Trim
ZeroFill = ZeroFill.PadLeft(4, "0")
since it will allways result in
ZeroFill = "0000"
and you're not using this value anyway.
Your connection.open and connection.close shoudl be all in the Else section, since you're not using it in if section. But this might be code cleanup consequence.
You should use parameters instead of direct query. Current version is risky for SQL Injection.
You shoudl use Using for Disposable objects.
3) Guessed version
I guess you want to trim leading zeros for validation, but pad your value with zeros for SQL search. In that case, your code should look somehow like this:
If TxtBoxW1.Text.Trim(" "c, "0"c).Length = 0 Then
MsgBox(" Please Enter a valid number", MessageBoxButtons.OK)
TxtBoxW1.Focus()
Else
Dim DS As New DataSet
Using Conn As New SqlConnection("DATABASE CONNECTION"), DA As New SqlDataAdapter("Select * From TABLENAME where COLNAME = #Param", Conn)
DA.SelectCommand.Parameters.Add(New SqlParameter("#Param", TxtBoxW1.Text.Trim.PadLeft(4, "0")))
Conn.Open()
DA.Fill(DS, "TABLENAME")
DataGridView1.DataSource = DS.Tables("TABLENAME")
End Using 'This will close the Connection for you
End If
My working code below:
Private Sub BtnSearch_Click(sender As System.Object, e As System.EventArgs) Handles BtnSearch.Click
SqlSelect = ""
sqlwhere = ""
expsql = sqlfrom & sqlwhere
Dim connection As New SqlConnection("database connection")
' Dim Command As New SqlCommand("Select * from table name where col1=#col1 = '" & TxtBoxW1.Text & "'", connection)
Dim Table As New DataSet
Dim sql As New SqlConnection
Dim ZeroFill As String
Dim ds as DataSet
connection.Open()
If TxtBoxW1.Text <> "" Then
ZeroFill = TxtBoxW1.Text.Trim
ZeroFill = ZeroFill.PadLeft(4, "0")
sqlwhere = ZeroFill
' MsgBox(" Please Enter a valid number", MessageBoxButtons.OK)
TxtBoxW1.Focus()
End If
adapter = New SqlDataAdapter("Select * From table name where col1 = " & sqlwhere & "", connection)
'adapter = New SqlDataAdapter(Sql, connection)
Command = New SqlCommandBuilder(adapter)
ds = New DataSet()
Try
adapter.Fill(ds, "Table Name")
DataGridView1.DataSource = ds1.Tables("Table Name")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
connection.Close()
End Sub

Syntax error in VB.NET application using SQL

Hi I have been learning VB.NET for about a month now. I am stuck on something I get an error message saying
Syntax error in union query.
The code in question is this.
Private Sub Button5_Click_1(sender As Object, e As EventArgs) Handles Button5.Click
Dim Builder As New OleDb.OleDbConnectionStringBuilder With
{
.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = IO.Path.Combine(Application.StartupPath, "C:\Users\Nige\Documents\Visual Studio 2012\Projects\MS_Access_SimplePassword\bin\Debug\Database1.mdb"),
.PersistSecurityInfo = True
}
LoginForm.txtUserName.Text = LoginForm.txtUserName.Text
If LoginForm.txtUserName.Text <> "" Then
End If
'do what you want to do
lblName.Text = LoginForm.txtUserName.Text
If lblName.Text = LoginForm.txtUserName.Text Then
Builder.Add("Jet OLEDB:Database Password", "password")
Using con As New OleDb.OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDb.OleDbCommand With
{
.Connection = con,
.CommandText =
<SQL>
("SELECT * FROM tblContacts WHERE number" = '55')
Identifier,
UserName,
UserPassword,
UserTimer
FROM tblContacts
</SQL>.Value
}
con.Open()
Dim Reader As OleDb.OleDbDataReader = cmd.ExecuteReader
If Reader.HasRows Then
Reader.Read()
TextBox1.Text = Reader.GetInt32(0).ToString
TextBox2.Text = Reader.GetString(1)
TextBox3.Text = Reader.GetString(2)
TextBox4.Text = Reader.GetString(3)
End If
End Using
End Using
End If
End Sub
The code above was supposed to when I click button5 search my "ms access database" called "tblContacts" for a row that references the number "55"
If my code looks strange in places it because I am a still on a learning path :)
Cheers
I can see a couple of errors in your code above:
Dim Builder As New OleDb.OleDbConnectionStringBuilder With
{
.Provider = "Microsoft.ACE.OLEDB.12.0",
.DataSource = "C:\Users\Nige\Documents\Visual Studio 2012\Projects\MS_Access_SimplePassword\bin\Debug\Database1.mdb"),
.PersistSecurityInfo = True
}
That Path.Combine with two absolute filename is logically wrong, but, nevertheless it works because Path.Combine is able to recognize that the two strings passed are two full filename and thus doesn't try to create an impossible path, but return directly the second string.
From MSDN on Path.Combine
The combined paths. If one of the specified paths is a zero-length
string, this method returns the other path. If path2 contains an
absolute path, this method returns path2.
Then, looking at your query, it clearly an invalid text for a select and thus you get the Syntax Error.
This could be the correct way to query the datatable assuming
You search for a row with a column named 'number'
This column is of text type text
One or more rows contains in this column a text equals to '55'
Dim sqlText = "SELECT Identifier, UserName, UserPassword, UserTimer " +
"FROM tblContacts WHERE number = '55'";
Using con = New OleDb.OleDbConnection(Builder.ConnectionString)
Using cmd = New OleDb.OleDbCommand(sqlText, con)
con.Open()
Using Reader = cmd.ExecuteReader
While Reader.Read()
TextBox1.Text = Reader.GetInt32(0).ToString
TextBox2.Text = Reader.GetString(1)
TextBox3.Text = Reader.GetString(2)
TextBox4.Text = Reader.GetString(3)
End While
End Using
End Using
End Using

update query dont work in vb.net

i want write update statement in code behind in vb.net.if ICCID is exists in tbl_ICCID then change status from 0 to 1 and Pic_Correct_ICCID.visible=true, if not exists , display "Not found".
i wrote this code but doesnt work and for all of ICCID that not exists in Tbl_ICCID Pic_Correct_ICCID.visible=true.
Please check my code and solve my problem.
in Cls_ICCID:
Public Function Update_Status(ByVal ICCID_No As String, ByVal status As Integer) As String
Try
Dim cmd As SqlCommand
Dim sql As String
Dim sql2 As String
Dim myConnection As SqlConnection = New SqlConnection()
myConnection.ConnectionString = "Data Source=TEHRANI\TEHRANI;Initial Catalog=GSMProduction;Persist Security Info=True;User ID=sa;Password=1"
**sql = "UPDATE Tbl_ICCID SET Status='" & status & "' Where ( ICCID = '" & ICCID_No & "' )"**
myConnection.Open()
cmd = New SqlCommand(sql, myConnection)
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
Update_Status = ""
Catch ex As SqlException
Update_Status = "Not found"
Catch ex As Exception
Update_Status = "Not connect to server"
End Try
End Function
in Frm_Packing
Private Sub Txt_ICCID_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Txt_ICCID.TextChanged
Pic_BP_Correct.Visible = False
Pic_BP_Wrong.Visible = False
Try
If Txt_ICCID.Text.Length = Txt_ICCID.MaxLength Then
lblError.Text = clsICCID.Update_Status(Txt_ICCID.Text.ToString(), 1)
lblError.ForeColor = Color.Red
stream = New System.IO.MemoryStream
pic_barcode = Nothing
cls.btnEncode(pic_barcode, Txt_ICCID.Text.Trim)
pic_barcode.Save(stream, System.Drawing.Imaging.ImageFormat.Png)
f = New IO.FileStream("C:\test55.png", IO.FileMode.Create, IO.FileAccess.ReadWrite)
b = stream.ToArray
f.Write(b, 0, b.Length)
f.Close()
Dim Val() = {stream.ToArray, Txt_ICCID.Text.Trim}
ds.Tables(0).Rows.Add(Val)
crp_report.SetDataSource(ds.Tables(0))
frm_crp.CrystalReportViewer1.ReportSource = crp_report
If lblError.Text = "" Then
Pic_BP_Correct.Visible = True
GBDoubleCheck.Visible = True
Txt_LabelBarcode.Focus()
Else
Pic_BP_Wrong.Visible = True
End If
End If
Catch ex As Exception
Pic_BP_Wrong.Visible = True
End Try
End Sub
Most probably due to sending status column value as string instead of int. You should remove those single-quotes. Also, this is really really bad practice to concat queries like that. Use CommandBuilders kind of thing or Typed DataSets for saving yourself against SQL injections.