How to return multiple values from a query vb.net - vb.net

one question how to store or return multiple queries result values into multiple variables.. I'm using a query that return 4 columns but how to.. individual store those results into 4 separate variables.. here is my code
Private Sub FrmAlumnos_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
txtCurrentUser.Text = Login.txtUser.Text
Dim strsql As String
strsql = "SELECT ""Agregar"", ""Modificar"", ""Eliminar"", ""Imprimir"" FROM ""Seguridad"".""GrupoPantallas"" WHERE ""IdGrupo"" = (SELECT ""IdGrupo"" FROM ""Seguridad"".""Users"" WHERE ""IdUsers"" = '" _
+ Me.txtCurrentUser.Text + "') AND ""IdPantalla"" = '" + Me.Name + "'"
Try
Using conexion As New Devart.Data.PostgreSql.PgSqlConnection(My.Settings.CNX_Principal)
Dim comando As New Devart.Data.PostgreSql.PgSqlCommand(strsql, conexion)
conexion.Open()
Dim registro As Devart.Data.PostgreSql.PgSqlDataReader = comando.ExecuteReader
If comando.ExecuteReader.Item(0) = 0 Then
btnNew.Visible = False
End If
If comando.ExecuteReader.Item(1) = 0 Then
btnEdit.Visible = False
End If
If comando.ExecuteReader.Item(2) = 0 Then
btnDelete.Visible = False
End If
If comando.ExecuteReader.Item(3) = 0 Then
btnPrint.Visible = False
End If
End Using
Catch ex As Exception
End Try
End Sub
I'm Using PostgreSQL just for you to know...

I think you might find a DataSet to be useful here. Something like:
Dim ds As New DataSet
Dim com As New SqlCommand
com.Connection = <yourconnectionstring>
com.CommandType = CommandType.Text
com.CommandText = "YOURSQLSTUFF"
Dim da As New DataAdapter
da.SelectCommand = com
da.Fill(ds)
ds.Tables(0).TableName = "FirstTable"
ds.Tables(0).PrimaryKey = New DataColumn() {ds.Tables(0).Columns("primaryKeyOfFirstTable")
ds.Tables(1).TableName = "SecondTable"
ds.Tables(1).PrimaryKey = New DataColumn() {ds.Tables(1).Columns("primaryKeyOfSecondTable")
Hope that helps!
-sf
EDIT: After some more searching, I found this link, which might help you out! It's postgreSQL specific!

You need to use the Read method of the DataReader:
Dim strsql As String
strsql = "SELECT ""Agregar"", ""Modificar"", ""Eliminar"", ""Imprimir"" FROM ""Seguridad"".""GrupoPantallas"" WHERE ""IdGrupo"" = (SELECT ""IdGrupo"" FROM ""Seguridad"".""Users"" WHERE ""IdUsers"" = '" _
+ Me.txtCurrentUser.Text + "') AND ""IdPantalla"" = '" + Me.Name + "'"
Try
Using conexion As New Devart.Data.PostgreSql.PgSqlConnection(My.Settings.CNX_Principal)
Dim comando As New Devart.Data.PostgreSql.PgSqlCommand(strsql, conexion)
conexion.Open()
Using registro As Devart.Data.PostgreSql.PgSqlDataReader = comando.ExecuteReader()
//Assuming that there is only a single row returned
If registro.Read()
btnNew.Visible = registro.GetBoolean(0)
btnEdit.Visible = registro.GetBoolean(1)
btnDelete.Visible = registro.GetBoolean(2)
btnPrint.Visible = registro.GetBoolean(3)
End While
End Using
End Using
Catch ex As Exception
End Try
You should also look into using parameters. It would make the code a little cleaner than using a concatenated string and would stop sql injection attacks.

Dim strsql As String
strsql = "SELECT ""Agregar"", ""Modificar"", ""Eliminar"", ""Imprimir"" FROM ""Seguridad"".""GrupoPantallas"" WHERE ""IdGrupo"" = (SELECT ""IdGrupo"" FROM ""Seguridad"".""Users"" WHERE ""IdUsers"" = '" _
+ Me.txtCurrentUser.Text + "') AND ""IdPantalla"" = '" + Me.Name + "'"
Try
Using conexion As New Devart.Data.PostgreSql.PgSqlConnection(My.Settings.CNX_Principal)
Dim comando As New Devart.Data.PostgreSql.PgSqlCommand(strsql, conexion)
conexion.Open()
Dim registro As Devart.Data.PostgreSql.PgSqlDataReader = comando.ExecuteReader
//This is the loop that you missed
While registro.Read()
If comando.ExecuteReader.Item(0) = 0 Then
btnNew.Visible = False
End If
If comando.ExecuteReader.Item(1) = 0 Then
btnEdit.Visible = False
End If
If comando.ExecuteReader.Item(2) = 0 Then
btnDelete.Visible = False
End If
If comando.ExecuteReader.Item(3) = 0 Then
btnPrint.Visible = False
End If
End While
End Using
Catch ex As Exception
End Try
I'm not sure if this is what you're trying to do, but all you have to do is loop through the DataReader as shown above.

Related

Use VB.NET Manipulate Microsoft Access Database

How can I make this work?
Private Sub ListView_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView.MouseClick
conndb = New OleDbConnection
conndb.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database1.accdb"
Try
conndb.Open()
Dim str As String
str = "Select * FROM customer WHERE CustomerID = '" & ListView.FocusedItem.Text & "'"
COMMAND = New OleDbCommand(str, conndb)
dr = COMMAND.ExecuteReader
If dr.Read = True Then
txtID.Text = dr("CustomerID")
txtFirstName.Text = dr("FirstName")
txtSurname.Text = dr("Surname")
txtAddress.Text = dr("Address")
txtCN1.Text = dr("ContactNo1")
txtCN2.Text = dr("ContactNo2")
txtEmail.Text = dr("EmailAddress")
txtRemarks.Text = dr("Remarks")
txtDebtStatus.Text = dr("DebtStatus")
txtDownPay.Text = dr("DownPayment")
txtDebtBal.Text = dr("DebtBal")
txtCustomerDate.Text = dr("Date")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conndb.Dispose()
End Try
End Sub
I need help on how can I make this run without errors, Im using ms access as my database source. There seems to be an error using this code, this code works perfectly fine with mysql but in ms access, it says data mistype error or something like that. Need your help, thanks
Remove the ' surrounding the field CustomerID in your query :
str = "Select * FROM customer WHERE CustomerID = '" & ListView.FocusedItem.Text & "'"
becomes :
str = "Select * FROM customer WHERE CustomerID = " & ListView.FocusedItem.Text
MS Access sees a string when you put an apostrophe, so there is a Type Mismatch Exception, because it is expecting a number...
However, this is a pretty bad idea as Parametrized queries are a better way of doing this (see : Why should I create Parametrized Queries ?)
Also, Use Using
So all in all, it's just another brick in the wall :
Private Sub ListView_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView.MouseClick
Using conndb As New OleDbConnection
conndb.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database1.accdb"
Try
conndb.Open()
Dim str As String
str = "Select * FROM customer WHERE CustomerID = #Customer"
Using COMMAND As New OleDbCommand(str, conndb)
COMMAND.Parameters.Add("#Customer", SqlDbType.Integer).Value = Integer.Parse(ListView.FocusedItem.Text)
dr = COMMAND.ExecuteReader
If dr.Read = True Then
txtID.Text = dr("CustomerID")
txtFirstName.Text = dr("FirstName")
txtSurname.Text = dr("Surname")
txtAddress.Text = dr("Address")
txtCN1.Text = dr("ContactNo1")
txtCN2.Text = dr("ContactNo2")
txtEmail.Text = dr("EmailAddress")
txtRemarks.Text = dr("Remarks")
txtDebtStatus.Text = dr("DebtStatus")
txtDownPay.Text = dr("DownPayment")
txtDebtBal.Text = dr("DebtBal")
txtCustomerDate.Text = dr("Date")
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub
Take a look at this sample code that I put together a while back. You can probably learn a lot from this.
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged, TextBox1.Click
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\your_path\Desktop\Northwind_2012.mdb"
Dim selectCommand As String
Dim connection As New OleDbConnection(connectionString)
'selectCommand = "Select * From MyExcelTable where Fname = '" & TextBox1.Text & "'"
'"SELECT * FROM Customers WHERE Address LIKE '" & strAddressSearch & "%'"
'or ending with:
'"SELECT * FROM Customers WHERE Address LIKE '%" & strAddressSearch & "'"
selectCommand = "Select * From MyExcelTable where Fname Like '" & TextBox1.Text & "%'"
Me.dataAdapter = New OleDbDataAdapter(selectCommand, connection)
With DataGridView1
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
End With
Dim commandBuilder As New OleDbCommandBuilder(Me.dataAdapter)
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(table)
Me.bindingSource1.DataSource = table
Dim data As New DataSet()
data.Locale = System.Globalization.CultureInfo.InvariantCulture
DataGridView1.DataSource = Me.bindingSource1
Me.DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Aqua
Me.DataGridView1.AutoResizeColumns( _
DataGridViewAutoSizeColumnsMode.AllCells)
End Sub

UPDATE statement in VB connecting to Access

I'm trying to update the position column in my access database but the problem is I'm having problem update that column while the rest of the column will not give out error message.
The error message: Syntax error in UPDATE statement, Microsoft JET database engine...
The code:
Dim myConnection As OleDbConnection = New OleDbConnection
Dim ds As New DataSet
Dim da As OleDbDataAdapter
Dim MaxRows As Integer
Dim i As Integer
Dim sql As String
Private Sub updateButton_Click(sender As Object, e As EventArgs) Handles updateButton.Click
Using myConnection = New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source =C:\LecturerDetail.mdb")
myConnection.Open()
Dim str As String
str = "UPDATE lecturer " & _
"SET [empName] = ?,[empId] = ?, [position] =?, [faculty] = ? " & _
" , [degree1] = ?, [degree2] = ?, [degree3] = ?,[degree] = ?, [empType] = ? " & _
" ,[icNo] = ?, [citizenship] = ?, [phoneNo] = ?, [email] = ?,[permitNo] = ? " & _
" , [permitStartDate] = ?, [permitEndDate] = ?, [pStatus] =?, [remark] =? " & _
" WHERE ([empId] = ?) "
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("#empName", nameTxt.Text)
cmd.Parameters.AddWithValue("#empId", empIdTxt.Text)
cmd.Parameters.AddWithValue("#position", positionComboBox.SelectedText)
cmd.Parameters.AddWithValue("#faculty", facultyComboBox.SelectedText)
cmd.Parameters.AddWithValue("#degree1", empDeg1.Text)
cmd.Parameters.AddWithValue("#degree2", empDeg2.Text)
cmd.Parameters.AddWithValue("#degree3", empDeg3.Text)
cmd.Parameters.AddWithValue("#degree", empDeg4.Text)
cmd.Parameters.AddWithValue("#empType", empTypeComboBox.SelectedText)
cmd.Parameters.AddWithValue("#icNo", icTxt.Text)
cmd.Parameters.AddWithValue("#citizenship", citizenshipComboBox.SelectedText)
cmd.Parameters.AddWithValue("#phoneNo", phoneTxt.Text)
cmd.Parameters.AddWithValue("#email", emailTxt.Text)
cmd.Parameters.AddWithValue("#permitNo", permitNoTxt.Text)
cmd.Parameters.AddWithValue("#permitStartDate", DateTimePicker1.Text)
cmd.Parameters.AddWithValue("#permitEndDate", DateTimePicker2.Text)
cmd.Parameters.AddWithValue("#pStatus", statusComboBox.Text)
cmd.Parameters.AddWithValue("#remark", remark.Text)
cmd.Parameters.AddWithValue("#empId", empIdTxt.Text)
Try
cmd.ExecuteNonQuery()
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("lecturer").Rows(i).Item(0) = empIdTxt.Text
ds.Tables("lecturer").Rows(i).Item(1) = nameTxt.Text
ds.Tables("lecturer").Rows(i).Item(2) = positionComboBox.Text
ds.Tables("lecturer").Rows(i).Item(3) = facultyComboBox.Text
ds.Tables("lecturer").Rows(i).Item(4) = empDeg1.Text
ds.Tables("lecturer").Rows(i).Item(5) = empDeg2.Text
ds.Tables("lecturer").Rows(i).Item(6) = empDeg3.Text
ds.Tables("lecturer").Rows(i).Item(7) = empDeg4.Text
ds.Tables("lecturer").Rows(i).Item(8) = empTypeComboBox.Text
ds.Tables("lecturer").Rows(i).Item(9) = icTxt.Text
ds.Tables("lecturer").Rows(i).Item(10) = citizenshipComboBox.Text
ds.Tables("lecturer").Rows(i).Item(11) = phoneTxt.Text
ds.Tables("lecturer").Rows(i).Item(12) = emailTxt.Text
ds.Tables("lecturer").Rows(i).Item(13) = permitNoTxt.Text
ds.Tables("lecturer").Rows(i).Item(14) = DateTimePicker1.Value
ds.Tables("lecturer").Rows(i).Item(15) = DateTimePicker2.Value
ds.Tables("lecturer").Rows(i).Item(16) = statusComboBox.Text
ds.Tables("lecturer").Rows(i).Item(17) = remark.Text
da.Update(ds, "lecturer")
ds.AcceptChanges()
myConnection.Close()
MsgBox("Record Updated")
Catch ex As Exception
MessageBox.Show(ex.Message & "-" & ex.Source)
End Try
End Using
End Sub
My code is to update the columns and allow user to navigate to the next record.
I'm new to visual basic so detail description and guidance are appreciated. Thanks. In addition, i'm trying to create auto notification system based on the dates. Anyone might enlighten me on which methods or applications to be used in visual basic to do it.
No need to create the update query hand. The CommandBuilder itself generate the necessary instructions to update the database.
Dim ds As New DataSet
Dim da As OleDbDataAdapter
Dim MaxRows As Integer
Dim i As Integer
Dim sql As String
Private Sub updateButton_Click(sender As Object, e As EventArgs) Handles updateButton.Click
Using myConnection = New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source =C:\LecturerDetail.mdb")
myConnection.Open()
Dim str As String
str = "SELECT * FROM lecturer WHERE ([empId] = #empId)"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("#empId", empIdTxt.Text)
Try
da = new OleDbDataAdapter(cmd)
da.Fill(ds,"lecturer")
ds.Tables("lecturer").Rows(i).Item(0) = empIdTxt.Text
ds.Tables("lecturer").Rows(i).Item(1) = nameTxt.Text
ds.Tables("lecturer").Rows(i).Item(2) = positionComboBox.Text
ds.Tables("lecturer").Rows(i).Item(3) = facultyComboBox.Text
ds.Tables("lecturer").Rows(i).Item(4) = empDeg1.Text
ds.Tables("lecturer").Rows(i).Item(5) = empDeg2.Text
ds.Tables("lecturer").Rows(i).Item(6) = empDeg3.Text
ds.Tables("lecturer").Rows(i).Item(7) = empDeg4.Text
ds.Tables("lecturer").Rows(i).Item(8) = empTypeComboBox.Text
ds.Tables("lecturer").Rows(i).Item(9) = icTxt.Text
ds.Tables("lecturer").Rows(i).Item(10) = citizenshipComboBox.Text
ds.Tables("lecturer").Rows(i).Item(11) = phoneTxt.Text
ds.Tables("lecturer").Rows(i).Item(12) = emailTxt.Text
ds.Tables("lecturer").Rows(i).Item(13) = permitNoTxt.Text
ds.Tables("lecturer").Rows(i).Item(14) = DateTimePicker1.Value
ds.Tables("lecturer").Rows(i).Item(15) = DateTimePicker2.Value
ds.Tables("lecturer").Rows(i).Item(16) = statusComboBox.Text
ds.Tables("lecturer").Rows(i).Item(17) = remark.Text
Dim cb As New OleDb.OleDbCommandBuilder(da)
da.Update(ds, "lecturer")
ds.AcceptChanges()
myConnection.Close()
MsgBox("Record Updated")
Catch ex As Exception
MessageBox.Show(ex.Message & "-" & ex.Source)
End Try
End Using
End Sub

LogIn form with user and admin using VB.net and Mysql

I want to get the privilege if it's admin or encoder but with this code I can't get any value... this is my code please help me
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
cn = New MySqlConnection
cn.ConnectionString = "server=localhost; userid=root; database=dp_inventory;"
Dim reader As MySqlDataReader
Try
cn.Open()
Dim sql As String
sql = "Select from dp_inventory.user_account where employeeID='" & UsernameTextBox.Text & "' and password='" & PasswordTextBox.Text & "' "
cmd = New MySqlCommand(sql, cn)
reader = cmd.ExecuteReader
Dim count As Integer
count = 0
While reader.Read
count = count + 1
End While
Dim users As String
users = "select privilege from user_account where employeeID='" & UsernameTextBox.Text & "'"
If count = 1 Then
If users = "admin" Then
frmAdminMain.Show()
ElseIf users = "encoder" Then
MainForm.Show()
End If
ElseIf count > 1 Then
frmAdminMain.Show()
Else
MsgBox("tryy again")
End If
Catch ex As Exception
MsgBox("Try again")
End Try
End Sub
There are quite a few errors in this code you wrote. Your first issue is you are simply trying to count without actually using a Sql counter.
Take a look at a code snippet from one of my applications here for a general idea
SelectStr = "SELECT MagPieces_Number,MagOperators_Number,MagFactor_Number,MagTotal_Number" & _
" FROM Parts_Mag WHERE Quote_Number_Id = #QuoteId and Quote_Rev_Id = #RevId and Part_Number_Id = #PartID and Part_Numeral_Id = #PartNumeral and SiteLocation = #Site"
SqlDataCmd = New SqlCommand(SelectStr, SqlConn)
SqlDataCmd.Parameters.AddWithValue("#QuoteId", QuoteId)
SqlDataCmd.Parameters.AddWithValue("#RevId", RevId)
SqlDataCmd.Parameters.AddWithValue("#PartId", PartNumber)
SqlDataCmd.Parameters.AddWithValue("#PartNumeral", PartNumeral)
SqlDataCmd.Parameters.AddWithValue("#Site", SiteLocation)
SqlReader = SqlDataCmd.ExecuteReader
While SqlReader.Read
MagPieces = SqlReader("MagPieces_Number").ToString
MagOperators = SqlReader("MagOperators_Number").ToString
MagFactor = SqlReader("MagFactor_Number").ToString
MagTotal = SqlReader("MagTotal_Number").ToString
End While
MagParticle.txtPiecesPerHour.Text = MagPieces
MagParticle.txtOperators.Text = MagOperators
MagParticle.txtMatFactor.Text = MagFactor
MagParticle.labMagTotal.Text = MagTotal
Catch ex As Exception
ErrorMessage(ex.message)
SqlReader.Close()
End Try
SqlReader.Close()
If you are simply looking for if your select statement has "Admin" or "Encoder" at the end, it would simply be something like this:
Dim empId as String = UsernameTextbox.Text
Dim SelectStr as String = "Select privilege from dp_inventory.user_account where employeeID=#empId
SqlDataCmd = New SqlCommand(SelectStr, SqlConn)
SqlDataCmd.Parameters.AddWithValue("#empId", empId)
Then read it with a reader. Once you have the general idea you should be able to take it from there! Im not quite sure why you need the count to begin with so you may want to just negate that portion out and simply read from your table based on the ID

Search through the database using a combobox, if an item is in a database, prompt will appear

Good day everyone.
I'm making a POS and Inventory Management System and I'm having a problem with this particular module as of now.
When adding an item to purchase order list, if an item is already in the purchaseorder database, the system will prompt that there is already a pending order. I've done the prompt, but the adding to the database was kinda messed up. It doesn't do a thing at all. The code there is working when I remove the ds.hasrows and while dr.read conditions. This is my code:
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Ceiling = CInt(txtCeiling.Text)
TotalQuantity = CurrentItemQuantity + CInt(txtPurchaseQty.Text)
If TotalQuantity > Ceiling Then
MsgBox("Exceeds Ceiling Point.")
Else
sqlString = "SELECT PRODUCT_ID FROM posinventory.purchaseorder WHERE purchaseorder.PRODUCT_ID = '" & cboProductID.Text & "'"
cmd = New MySqlCommand(sqlString, con)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
If CurrentItem = dr.Item("PRODUCT_ID") Then
MsgBox("Product has pending order.")
cboProductID.Focus()
Else
sqlString = "INSERT INTO posinventory.purchaseorder (PRODUCT_ID, PURCHASE_QUANTITY, DATE_PURCHASED, TIME_PURCHASED) VALUES (" & cboProductID.Text & ", '" & txtPurchaseQty.Text & "', '" & txtDate.Text & "', '" & txtTime.Text & "')"
Try
cmd = New MySqlCommand(sqlString, con)
dr = cmd.ExecuteReader
dr.Close()
Catch ex As Exception
MsgBox("Error saving to database. Error is: " & ex.Message)
Exit Sub
End Try
MsgBox("Transaction Complete.")
lvOrderList.Items.Clear()
sqlString = "SELECT posinventory.purchaseorder.TRANSACTION_ID, posinventory.products.PRODUCT_ID, posinventory.products.PRODUCT_NAME, posinventory.products.SUPPLIER_NAME, posinventory.purchaseorder.PURCHASE_QUANTITY, posinventory.purchaseorder.DATE_PURCHASED, posinventory.purchaseorder.TIME_PURCHASED FROM posinventory.purchaseorder, posinventory.products WHERE posinventory.purchaseorder.PRODUCT_ID = posinventory.products.PRODUCT_ID"
cmd = New MySqlCommand(sqlString, con)
da = New MySqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "Table")
Dim i As Integer = 0
Dim j As Integer = 0
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
itemcol(j) = ds.Tables(0).Rows(i)(j).ToString()
Next
Dim lvi As New ListViewItem(itemcol)
Me.lvOrderList.Items.Add(lvi)
Next
grpCreateOrder.Enabled = False
grpOrderList.Enabled = True
cboProductID.SelectedIndex = -1
txtPurchaseQty.Text = ""
txtDate.Text = ""
txtTime.Text = ""
txtProductName.Text = ""
txtSupplier.Text = ""
txtQty.Text = ""
txtCeiling.Text = ""
btnBack.Enabled = True
End If
End While
End If
dr.Close()
End If
End Sub
I think its because you are inside of a loop using a cmd and dr. While you are in there you are then defining a new cmd and dr.
Try using different names eg cmd2, dr2.

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.