InvalidCastException when retrieving data from SqlDataReader - sql

How can I get rid of:
System.InvalidCastException: 'Conversion from string "Type" to type
'Integer' is not valid.'"
On the line:
Dim usertype = Reader.GetString("Type")
This is my full code:
Private Sub OKbt1_Click(sender As Object, e As EventArgs) Handles OKbt1.Click
Call Connect() ' [ connection to module ]'
Dim Reader As SqlDataReader
Try
Dim command As New SqlCommand("select * from uinfo where password = '" & PASStb2.Text & "'", sqlConn)
Reader = command.ExecuteReader
Reader.Read()
Dim count As Integer = 0
While Reader.Read
count = count + 1
End While
If count = 1 Then
' ** MY ERROR **
Dim usertype = Reader.GetString("Type")
If usertype = "admin" Then
'MsgBox("username and password are correct")
MAIN_MENU.Show()
For a = 0 To 500
Next
Me.Hide()
sqlConn.Close()
sqlConn.Dispose()
ElseIf usertype = "user" Then
For a = 0 To 500
Next
Me.Hide()
'MsgBox("username and password are correct")
USERMENU.Show()
End If
ElseIf count > 1 Then
MsgBox("username and password are duplicate")
Else
MsgBox("username and password are not correct")
End If
sqlConn.Close()
Catch ex As SqlException
MsgBox(ex.Message)
Finally
sqlConn.Dispose()
End Try
End Sub

SqlDataReader.GetString Method (Int32) needs an integer (column index) as a parameter. So you need
Dim usertype as String = Cstr(Reader("Type"))
or
Dim usertype = Reader.GetString(Reader.GetOrdinal("Type"))
or
Dim usertype = Reader.GetFieldValue(Of String)("Type")
Be aware that non of those posibilites can handle DBnull.

'Reader.GetString' accepts an integer parameter, not a string. Or, do
Reader.Item("Type").ToString()

Declare usertype as Dim usertype as String and then assign value to it like usertype = Reader.Item("Type").ToString().
also you need to check value return by Reader.GetString("Type") it might be null. Turn "Option Strict" On It will help in the long run.

**Dim usertype = Reader.GetString("Type") // MY ERROR**
You are passing a value of string which obviously is wrong
GetString function accepts integer.
You might want to instantiate a data which is integer and pass it through getstring.
Dim usertype = Reader.GetString(data)

Use parameters. I let the server do the counting. Saves you some lines of code.
Private Sub OKbt1_Click(sender As Object, e As EventArgs) Handles OKbt1.Click
Call Connect() ' [ connection to module ]'
Dim Reader As SqlDataReader
Try
Using cmd As New SqlCommand("select usertype, Count(*) from uinfo Group By usertype where [password] = #password;", sqlConn)
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = PASStb2.Text
Reader = cmd.ExecuteReader()
If Reader.HasRows Then
Reader.Read()
Dim usertype As String = Reader.GetString(0)
Dim count As Integer = Reader.GetInt32(1)
If count = 1 Then
If usertype = "admin" Then
MAIN_MENU.Show()
Hide()
ElseIf usertype = "user" Then
USERMENU.Show()
Hide()
End If
ElseIf count > 1 Then
MsgBox("username and password are duplicate")
End If
Else
MsgBox("username and password are not correct")
End If
End Using
Catch ex As Exception
MsgBox(ex.Message)
Finally
sqlConn.Close()
sqlConn.Dispose()
End Try
End Sub

It is because you may not getting data from "Reader" object properly
Try this instead :
Dim command As SqlCommand = New SqlCommand("SELECT * FROM uinfo WHERE password = '" & PASStb2.Text & "'", connection)
connection.Open()
Dim READER As SqlDataReader = command.ExecuteReader()
If READER.HasRows Then
While READER.Read()
Console.WriteLine("{0}" & vbTab & "{1}", READER.GetInt32(0), READER.GetString(1))
End While
Else
Console.WriteLine("No rows found.")
End If
READER.Close()

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

Attempting to validate username (email address) and password - having issues - vb.net

I have a Windows Form app that is not properly validating the user input information. Need some help.
I inserted the Microsoft Login form and am writing code to verify the user credentials. Using an Access DB to store and retrieve info. Two tables - one for email address and another for password.
I verify format of the email addy using regex. This works very well.
I validate the email address is in correct form and verify it is in the table (this works well). Then I attempt to read the password (appears this is not working as expected) and then read both bits of information from the tables. Next, I test to make sure both are present. If both are present control is passed to another form.
My issue is reading/verifying the password.
Here is my Visual Studio VB.net code.
Private Sub OK_Click(sender As System.Object, e As System.EventArgs) Handles OK.Click
Try
If MsgBox("Is your information correct?", MsgBoxStyle.YesNo, "M&P Records") = MsgBoxResult.Yes Then
Dim pattern As String = "^[A-Z][A-Z|0-9|]*[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?#[a-z][a-z|0-9|]*\.([a-z][a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$"
Dim match As System.Text.RegularExpressions.Match = Regex.Match(txtUsername.Text.Trim(), pattern, RegexOptions.IgnoreCase)
If (match.Success) Then
Try
If i = 0 Then
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
'Change the following to your access database location
dataFile = "\11_2017_Spring\CSCI-2999_Capstone\DB_M&PRecords.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
i = 1
End If
Catch ex As Exception
' An error occured! Show the error to the user and then exit.
MessageBox.Show(ex.Message)
End Try
'the query:
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [EmailAddress] WHERE [emailAddress] = '" & txtUsername.Text & "'", myConnection)
Dim com As OleDbCommand = New OleDbCommand("SELECT * FROM [Password] WHERE [Password] = '" & txtPassword.Text & "'", myConnection2)
Dim dr As OleDbDataReader = cmd.ExecuteReader()
Dim drp As OleDbDataReader = com.ExecuteReader()
' the following variable is hold true if EmailAddress is found, and false if EmailAddress is not found
Dim userFound As Boolean = False
' the following variable is hold true if Password is found, and false if Password is not found
Dim passwordFound As Boolean = False
' the following variables will hold the EmailAddress and Password if found.
Dim EmailAddressText As String = ""
Dim PasswordText As String = ""
'if found:
While dr.Read()
userFound = True
EmailAddressText = dr("EmailAddress").ToString
End While
While drp.Read()
passwordFound = True
PasswordText = drp("Password").ToString
End While
'checking the result
If userFound = True And passwordFound = True Then
frmMain.Show()
frmMain.Label1.Text = "Welcome " & EmailAddressText & " "
Else
MsgBox("Sorry, username or password not found", MsgBoxStyle.OkOnly, "M&P Records - Invalid Login")
With txtPassword
.Clear()
End With
With txtUsername
.Clear()
.Focus()
End With
End If
Else
MessageBox.Show("Please enter a valid email address", "M&P Records - Email Check")
With txtPassword
.Clear()
End With
With txtUsername
.Clear()
.Focus()
End With
End If
End If
Catch ex As Exception
' An error occured! Show the error to the user and then exit.
MessageBox.Show(ex.Message)
End Try
End Sub
Well first your approach isn't really safe due to the fact the the password isn't encrypted and that either there is no link between email and password ideally you would have table for example:
USER
--UID
--Email
PASS
--ID
--UID
--PASS
And you would hash your password for example sha512 furthermore for more security you would use Salt and certificates to secure the database connection.
Then you could do:
Hash current password in textbox and execute:
"SELECT USER.Email FROM USER,PASS WHERE USER.Email='TEXTBOX_EMAIL' AND USER.UID = PASS.UID"
Check if you have result if yes your connected.
However I tried to correct a bit what you did in the above code. Having used only SQLClient and not Olecommand i tried to keep what you did so there might be few syntax errors but should be ok:
Try
If MsgBox("Is your information correct?", MsgBoxStyle.YesNo, "M&P Records") = MsgBoxResult.Yes Then
Dim pattern As String = "^[A-Z][A-Z|0-9|]*[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?#[a-z][a-z|0-9|]*\.([a-z][a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$"
Dim match As System.Text.RegularExpressions.Match = Regex.Match(txtUsername.Text.Trim(), pattern, RegexOptions.IgnoreCase)
If (match.Success) Then
Dim passwordFound As Boolean
Dim userFound As Boolean
Using con As New SqlClient.SqlConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source =\ 11_2017_Spring\CSCI-2999_Capstone\DB_M&PRecords.accdb")
'Using to make sure connection is disposed
'Open connection
con.Open()
'Prepare sql
Dim command As New OleDbCommand("SELECT [emailAddress] FROM [EmailAddress] WHERE [emailAddress] = '" & txtUsername.Text & "';", con)
'Create the reader
Dim reader As OleDbDataReader = command.ExecuteReader()
Dim Id As String = ""
' Call Read before accessing data.
While reader.Read()
'Get data
Id = reader(0)
End While
'Close Reader
reader.Close()
If Id <> "" Then
'User found
userFound = True
'Prepare the second sql
Dim command2 As New OleDbCommand("SELECT [Password] FROM [Password] WHERE [Password] = '" & txtPassword.Text & "';", con)
'Prepare second reader
Dim reader2 As OleDbDataReader = command.ExecuteReader()
Dim Pass As String = ""
' Call Read before accessing data.
While reader2.Read()
'Get tdata
Pass = reader2(0)
End While
reader.Close()
If Pass <> "" Then
'Pass found
passwordFound = True
Else
passwordFound = False
End If
Else
userFound = False
End If
'Close connection
con.Close()
'Clear connection pool
SqlConnection.ClearPool(con)
End Using
'checking the result
If userFound = True And passwordFound = True Then
frmMain.Show()
frmMain.Label1.Text = "Welcome " & EmailAddressText & " "
Else
MsgBox("Sorry, username or password not found", MsgBoxStyle.OkOnly, "M&P Records - Invalid Login")
With txtPassword
.Clear()
End With
With txtUsername
.Clear()
.Focus()
End With
End If
Else
MessageBox.Show("Please enter a valid email address", "M&P Records - Email Check")
With txtPassword
.Clear()
End With
With txtUsername
.Clear()
.Focus()
End With
End If
End If
Catch ex As Exception
' An error occured! Show the error to the user and then exit.
MessageBox.Show(ex.Message)
End Try
Decided to combine the email and passwords into one table. Made everything easier for now. Thanks for your help and suggestions.

An unhandled exception of tpe 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Index was out of range. Must be non-negative and less than the size of the collection.
The above unhandled exception shows when i run below code :
Private Sub chUser()
conn = New SqlConnection(conStr)
conn.Open()
myConn.clName = clNameDGV.SelectedRows.Item(0).Cells(0).Value //EXCEPTION SHOWS FOR THIS LINE
Dim comStr As String = "Select Count(*) from Login_Detail Where Clinic_Name = '" & clNameDGV.SelectedRows.Item(0).Cells(0).Value & "'"
Dim comm As New SqlCommand(comStr, conn)
Dim i As Integer = comm.ExecuteScalar()
If i = 0 Then
If MessageBox.Show("No User Information found for '" + clNameDGV.SelectedRows.Item(0).Cells(0).Value + "'." + vbNewLine + "Do you want to enter new user details ?", "No Users Found", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = vbYes Then
Dim nf As New CreateUser
nf.TopMost = True
nf.ShowDialog(Me)
End If
End If
Dim nf1 As New LoginForm
nf1.TopMost = True
nf1.ShowDialog(Me)
conn.Close()
End Sub
I have only one column with multiple rows in my datagridview. I run above function on doubleclick event of datagridview.
As you have a one-column DGV, you only need to use the .SelectedCells property, and you should check that only one cell is selected, something like this:
Private Sub ChUser()
If clNameDGV.SelectedCells.Count <> 1 Then
' not exactly one row was selected
Exit Sub
End If
Dim clinicName As String = CStr(clNameDGV.SelectedCells.Item(0).Value)
Dim nFoundRecords As Integer
Dim conn As SqlConnection = Nothing
Try
conn = New SqlConnection(conStr)
conn.Open()
myConn.clName = clinicName
Dim sql As String = "SELECT COUNT(*) FROM Login_Detail WHERE Clinic_Name = #ClinicName"
Using cmd As New SqlCommand(sql, conn)
'TODO: Set the .SqlDbType parameter correctly.
'TODO: Add the .Size parameter to match the setting in the database.
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#ClinicName", .SqlDbType = SqlDbType.NVarChar, .Value = clinicName})
nFoundRecords = CInt(cmd.ExecuteScalar())
End Using
conn.Close()
Finally
If conn IsNot Nothing Then
conn.Dispose()
End If
End Try
If nFoundRecords = 0 Then
Dim message As String = "No User Information found for '" & clinicName & "'." & vbNewLine & "Do you want to enter new user details?"
Dim userChoice As DialogResult = MessageBox.Show(message, "No Users Found", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If userChoice = DialogResult.OK Then
Dim nf As New CreateUser
nf.TopMost = True
nf.ShowDialog(Me)
End If
End If
Dim nf1 As New LoginForm
nf1.TopMost = True
nf1.ShowDialog(Me)
End Sub
Please note how I have used CStr and CInt in appropriate places. If you use Option Strict On then it will point out for you where you should make explicit conversions (among other things). Also, I split up some lines into several lines to make it easier to read, and hence easier to edit.

Detecting if data exists for OleDB COUNT query

I'm trying to pull data from ACCESS database.
As it is, the code works, and gives no errors...
However, I can't seem to be able to display a messagebox if the record doesn't exist. It simply returns an empty string.
Using dbCon = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source = '" & Application.StartupPath & "\Res\T500G.accdb'")
dbCon.Open()
Dim Query1 As String = "SELECT SUM(Total) FROM [T500] WHERE Pro=#Pro"
Dim cmd1 As OleDb.OleDbCommand = New OleDbCommand(Query1, dbCon)
cmd1.Parameters.AddWithValue("#Pro", ComboBoxBP.SelectedItem.ToString)
Dim reader As OleDb.OleDbDataReader
reader = cmd1.ExecuteReader
While reader.Read()
TextBox1.Text = reader.GetValue(0).ToString
End While
reader.Close()
dbCon.Close()
End Using
I've tried using If reader.hasrows then display result in textbox, else show messagebox etc, but it doesn't work.
If reader.HasRows Then
While reader.Read()
TextBox1.Text = reader.GetValue(0).ToString
End While
Else
MessageBox.Show("asd")
End If
If I remove the .ToString from reader.GetValue(0) I get an error if the selected item from the combobox doesn't exist in the database. Cannot convert DBNull to integer or something.
So my question is, how to display a messagebox if the record "#Pro" doesn't exist?
Thanks~
Fixed(Workaround) with this
Dim ValueReturned As String
While reader.Read()
ValueReturned = reader.GetValue(0).ToString
If ValueReturned = "" Then
MessageBox.Show("Not Found", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
MetroTextBox1.Text = ValueReturned
End If
End While
Using OleDbDataReader is suboptimal for your query because it is never going to return a set of records to traverse:
Dim sql = "SELECT SUM(...=#p1"
' rather than sprinkling you connection string all over
' the app, you can make a function returning one
Using conn As OleDbConnection = GetConnection(),
cmd As New OleDbCommand(sql, GetConnection())
conn.Open())
' ToDo: Check that ComboBoxBP.SelectedItems.Count >0 before this
cmd.Parameters.AddWithValue("#p1", ComboBoxBP.SelectedItem.ToString)
' execute the query, get a result
Dim total = cmd.ExecuteScalar
' if there is no matches, OleDb returns DBNull
If total Is System.DBNull.Value Then
' no matches
MessageBox.Show("No matching records!"...)
Else
MessageBox.Show("The Total is: " & total.ToString()...)
End If
End Using ' disposes of the Connection and Command objects
Alteratively, you could use If IsDBNull(total) Then.... If you want, you can also convert it:
Dim total = cmd.ExecuteScalar.ToString()
' DBNull will convert to an empty string
If String.IsNullOrEmpty(total) Then
MessageBox.Show("No Soup For You!")
Else
...
End If
You could change your query to (this is for SQL-Server):
IF EXISTS (SELECT * FROM [T500] WHERE Pro = #Pro) SELECT SUM(Total) FROM [T500] WHERE Pro = #Pro ELSE SELECT 'Not Found'
And change your code to:
Dim ValueReturned As String
While reader.Read()
ValueReturned = reader.GetValue(0).ToString
End While
If ValueReturned Is Nothing OrElse ValueReturned = "Not Found" Then
MessageBox.Show("Not Found", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
TextBox1.Text = ValueReturned
End If

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.