VB.net - If 1 then "Yes" if 0 then "no" - sql

I have Database Software I am trying to make. The problem is I can't seem to find how to make this work, i'm new to this whole thing and have figured a lot out on my own but I can't seem to do this simple task?
I have a listView that displays the data from the SQl everything works great EXCEPT I need the dropdaown box the say yes or no but import into the SQL database a 1 or 0 and also in my list view i need it to display a Yes or a No instead of a 1 or a 0 ? Thanks IN Advance
Code:
Imports System.Data.SqlClient
Imports System.Data
Public Class cmListAll
Dim cn As New SqlConnection
Dim cmd As SqlCommand
Dim dr As SqlDataReader
Private Sub frmReg_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
With Me.cboActive
.Items.Add("Yes")
.Items.Add("No")
.SelectedIndex = 0
End With
Call connectMeToSQLServer("Data Source=Database;Initial Catalog=db_XXX;Integrated Security=False;Uid=sa; Pwd=PASS;")
Call showList()
End Sub
Private Sub cboActive_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
e.Handled = True
End Sub
Private Sub cboACTIVE_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.txtCredentials.Focus()
End Sub
Sub connectMeToSQLServer(ByVal cnString As String)
Try
With cn
If .State = ConnectionState.Open Then .Close()
.ConnectionString = cnString
.Open()
End With
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End Sub
Function INC() As Boolean
For Each t In Me.GroupBox2.Controls
If TypeOf t Is TextBox Or TypeOf t Is ComboBox Then
End If
If t.Text = "" Then
INC = True
End If
Next
End Function
Sub showList()
cmd = New SqlCommand
cmd.Connection = cn
cmd.CommandText = "Select * from [Case Managers]"
dr = cmd.ExecuteReader
Me.ListView1.Items.Clear()
While dr.Read
With Me.ListView1
.Items.Add(dr(0))
With .Items(.Items.Count - 1).SubItems
.Add(dr(1))
.Add(dr(2))
.Add(dr(3))
.Add(dr(4))
End With
End With
End While
dr.Close()
End Sub
Sub clearMe()
For Each t In Me.GroupBox2.Controls
If TypeOf t Is TextBox Then
If t.Text <> "" Then
t.text = ""
End If
Me.cmdNew.Enabled = True
Me.cmdSave.Text = "&Save"
Me.cmdSave.Enabled = False
Me.cmdDelete.Enabled = False
Me.cboActive.SelectedIndex = 0
End If
Next
End Sub
Private Sub cmdNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdNew.Click
For Each t In Me.GroupBox2.Controls
If TypeOf t Is TextBox Then
If t.Text <> "" Then
t.text = ""
End If
End If
Next
Me.cmdNew.Enabled = False
Me.cmdSave.Tag = "SAVE"
Me.cmdSave.Text = "&Save"
Me.cmdSave.Enabled = True
Me.GroupBox2.Enabled = True
Me.txtfirstname.Focus()
End Sub
Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
Select Case Me.cmdSave.Tag
Case "SAVE"
If INC() = True Then
MsgBox("Please Complete All Fields!", MsgBoxStyle.Exclamation, "")
Exit Sub
Else
cmd = New SqlCommand
cmd.CommandText = "Insert Into [Case Managers](Firstname,Lastname,Credentials,Active) Values('" & Me.txtfirstname.Text & "', '" & Me.txtlastname.Text & "', '" & Me.txtCredentials.Text & "', '" & Me.cboActive.Text & "' )"
cmd.Connection = cn
cmd.ExecuteNonQuery()
MsgBox("Successfully Save!", MsgBoxStyle.Information, "")
End If
Case Else
cmd = New SqlCommand
cmd.Connection = cn
cmd.CommandText = "Update [Case Managers] Set firstname='" & Me.txtfirstname.Text & "', lastname='" & Me.txtlastname.Text & "', credentials='" & Me.txtCredentials.Text & "', active='" & Me.cboActive.Text & "' Where CaseMangerID = " & Me.ListView1.SelectedItems(0).Text & ""
cmd.ExecuteNonQuery()
MsgBox("Successfully Updated!", MsgBoxStyle.Information, "")
End Select
clearMe()
showList()
End Sub
Private Sub ListView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.DoubleClick
cmd = New SqlCommand
cmd.Connection = cn
cmd.CommandText = "Select * from [Case Managers] Where CaseMangerID = " & Me.ListView1.SelectedItems(0).Text & " "
dr = cmd.ExecuteReader
dr.Read()
Me.txtfirstname.Text = dr(1)
Me.txtlastname.Text = dr(2)
Me.txtCredentials.Text = dr(3)
Me.cboActive.Text = dr(4)
dr.Close()
Me.GroupBox2.Enabled = True
Me.cmdSave.Enabled = True
Me.cmdSave.Tag = "UPDATE"
Me.cmdSave.Text = "&Update"
Me.cmdDelete.Enabled = True
End Sub
Private Sub cmdDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDelete.Click
If MsgBox("Delete This Record?", MsgBoxStyle.Question + MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
cmd = New SqlCommand
cmd.Connection = cn
cmd.CommandText = "Delete from [Case Managers] Where CaseMangerID =" & Me.ListView1.SelectedItems(0).Text & " "
cmd.ExecuteNonQuery()
MsgBox("Successfully Deleted!", MsgBoxStyle.Information, "")
Me.cmdDelete.Enabled = False
Me.cmdSave.Enabled = False
Call clearMe()
Call showList()
Else
Exit Sub
End If
End Sub

I assume you're looking at this line:
Me.cboActive.Text = dr(4)
? That's the only thing that looked to me like it might be displaying a yes/no field. You could just put a simple If/Else block there, but as there are several other significant flaws in how this code is structured, I thought it would be useful to re-write that whole method for you:
Private Sub ListView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.DoubleClick
'Would be better to specify column names here
Dim sql As String = "Select * from [Case Managers] Where CaseMangerID = #CaseManager"
'Best practices in most cases call for creating a new connection object for each query
Using cn As New SqlConnection("connection string here"), _
cmd As New SqlCommand(sql, cn)
'This is how to do string substitution in sql to protect against sql injection
cmd.Parameters.Add("#CaseManager", SqlDbType.Int).Value = CInt(Me.ListView1.SelectedItems(0).Text)
Using dr As SqlDataReader = cmd.ExecuteReader()
dr.Read()
Me.txtfirstname.Text = dr(1)
Me.txtlastname.Text = dr(2)
Me.txtCredentials.Text = dr(3)
Me.cboActive.Text = If(dr(4)=0,"No","Yes")
dr.Close()
End Using
End Using 'No need to close the connection. The Using block takes care of it
'The old code would have the left the connection open if an exception was thrown,'
' which could eventually lock you out of the database
Me.GroupBox2.Enabled = True
Me.cmdSave.Enabled = True
Me.cmdSave.Tag = "UPDATE"
Me.cmdSave.Text = "&Update"
Me.cmdDelete.Enabled = True
End Sub
You'll need to do something similar later on to invert this for updates/inserts.

You can use DisplayMember/ValueMember pair:
Dim dict As New Dictionary(Of Integer, String)
dict.Add(0, "No")
dict.Add(1, "Yes")
With Me.cboActive
.DisplayMember = "Value"
.ValueMember = "Key"
.DataSource = dict.ToList()
.SelectedIndex = 0
End With
Dictionary may not the best choice of class here, but works as a proof of concept.
Then just use cboActive.SelectedValue and pass that to the SQL query.

Related

Debugging in vb.net?

I'm new to coding, I've been working on my project of online billing system using Visual Basic.
The complete coding has been done, but while running the code, the totalitems and totalamt is not being calculated. Can you please debug or guide me how can I resolve this issue...
It shows errors like
1.conversion of type dbnull to string is not valid
2.string or binary data would be truncated.
Public Class billing
Dim disAmount As Double
Dim getProducID As Integer
Dim getStocks As Integer
Dim validatestock As Integer
Dim getUnitPrice As Double
Dim loadqty As Double
Dim discount As Boolean
Private Sub billing_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
getTransactionID()
GenerateInvoiceNo()
fillComboproduct()
End Sub
Private Sub getTransactionID()
Try
Dim trans As New Random
Dim numbers As Integer = trans.Next(1, 1000000)
Dim digitss As String = numbers.ToString("000000")
txttrans.Text = digitss
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub GenerateInvoiceNo()
lblInvoice.Text = "INV-" & GetUniqueKey(8)
End Sub
Public Shared Function GetUniqueKey(ByVal maxSize As Integer) As String
Dim chars As Char() = New Char(61) {}
chars = "123456789".ToCharArray()
Dim data As Byte() = New Byte(0) {}
Dim crypto As New RNGCryptoServiceProvider()
crypto.GetNonZeroBytes(data)
data = New Byte(maxSize - 1) {}
crypto.GetNonZeroBytes(data)
Dim result As New StringBuilder(maxSize)
For Each b As Byte In data
result.Append(chars(b Mod (chars.Length)))
Next
Return result.ToString()
End Function
Private Sub fillComboproduct()
Dim query As String = "Select productname From product order by productname"
Dim dtproduct As DataTable = getDataTable(query)
txtproductame.DataSource = dtproduct
txtproductame.DisplayMember = "productname"
' txtproductame.ValueMember = "productID"
If txtproductame.Items.Count > 0 Then
txtproductame.SelectedIndex = 0
End If
End Sub
Private Sub clear()
txtproductID.Text = ""
txtprice.Text = ""
txtQuantity.Text = ""
txtBalance.Text = ""
txttotal.Text = ""
txtAmtPaid.Text = ""
lblSubTotal.Text = "0"
txtproductame.Text = ""
lblTotalAmount.Text = "0.00"
lblSubTotal.Text = "0.00"
lblTotalItems.Text = "0"
txtprice.Text = ""
txtQuantity.Text = "1"
txttotal.Text = "0.00"
End Sub
Private Sub addbills()
Try
Sql = "INSERT INTO bills VALUES( '" & txtproductID.Text & "', '" & txtproductame.Text & "','" & txtQuantity.Text & "', '" & txtprice.Text & "','" & txttotal.Text & "', '" & lblInvoice.Text & "', '" & Date.Today & "')"
ConnDB()
cmd = New SqlCommand(sqL, conn)
Dim i As Integer
i = cmd.ExecuteNonQuery
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
conn.Close()
End Try
End Sub
Private Sub loadbills()
Try
Sql = "SELECT productID,productname,qty,unitprice FROM bills WHERE invoiceno = '" & Trim(lblInvoice.Text) & "' "
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
dgw.Rows.Clear()
Do While dr.Read = True
dgw.Rows.Add(dr(0), dr(1), dr(2), dr(3))
Loop
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub totalamt()
Try
Sql = "SELECT sum(totalamt) FROM bills where invoiceno = '" & Trim(lblInvoice.Text) & "' "
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Do While dr.Read = True
lblTotalAmount.Text = dr(0)
Loop
Catch ex As Exception
End Try
End Sub
Private Sub gettotalitems()
Try
Sql = "SELECT sum(qty) FROM bills where invoiceno = '" & Trim(lblInvoice.Text) & "' "
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Do While dr.Read = True
lblTotalItems.Text = dr(0)
Loop
Catch ex As Exception
End Try
End Sub
Private Sub saveitems()
Try
Sql = "INSERT INTO transactionDetails VALUES('" & txttrans.Text & "','" & lblInvoice.Text & "', '" & lblTotalItems.Text & "', '" & lblTotalAmount.Text & "', '" & txtAmtPaid.Text & "','" & txtBalance.Text & "', '" & cmdpayment.Text & "', '" & Date.Today & "')"
ConnDB()
cmd = New SqlCommand(sqL, conn)
Dim i As Integer
i = cmd.ExecuteNonQuery
If i > 0 Then
MsgBox("Billing Details Successfully saved", MsgBoxStyle.Information, "Saves Billing Details")
Else
MsgBox("Failed in Saves Billing Details", MsgBoxStyle.Information, "Saves Billing Details")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
conn.Close()
End Try
End Sub
Private Sub txtproductame_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtproductame.SelectedIndexChanged
Try
ConnDB()
Dim da As New SqlDataAdapter(("select * from product where productname ='" & Trim(txtproductame.Text) & "'"), conn)
Dim dt As New DataTable
da.Fill(dt)
If dt.Rows.Count > 0 Then
Me.txtprice.Text = dt.Rows(0).Item("unitprice") & ""
Me.txtproductID.Text = dt.Rows(0).Item("productID") & ""
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub txtQuantity_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtQuantity.TextChanged
txttotal.Text = Val(txtQuantity.Text) * Val(txtprice.Text)
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Me.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
getTransactionID()
GenerateInvoiceNo()
End Sub
Private Sub BindToText()
Try
With dgw
lblSubTotal.Text = Val(.SelectedRows(0).Cells("qty").Value) * Val(.SelectedRows(0).Cells("price").Value)
.SelectedRows(0).Cells("amt").Value = lblSubTotal.Text
End With
Catch ex As Exception
End Try
End Sub
Private Sub dgw_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgw.CellClick
BindToText()
End Sub
Private Sub dgw_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgw.SelectionChanged
BindToText()
End Sub
Private Sub txtAmtPaid_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtAmtPaid.KeyPress
Dim ch As Char = e.KeyChar
If Char.IsLetter(ch) Then 'Ristricting To Input Only Digits(any number)
e.Handled = True
End If
End Sub
Private Sub txtQuantity_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtQuantity.KeyPress
Dim ch As Char = e.KeyChar
If Char.IsLetter(ch) Then 'Ristricting To Input Only Digits(any number)
e.Handled = True
End If
End Sub
Private Sub btnload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnload.Click
Try
txttotal.Text = Val(txtprice.Text) * Val(txtQuantity.Text)
If txtproductame.Text = "" Or txtQuantity.Text = "" Then
MsgBox("Please enter a product Or Quantity before you click load button")
Else
addbills()
loadbills()
totalamt()
gettotalitems()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
txttotal.Text = ""
txtQuantity.Text = ""
End Sub
Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
If dgw.Rows.Count = 0 Then
MsgBox("Please load drugs in the cart before saving", MsgBoxStyle.Exclamation, "Validation")
Exit Sub
End If
If txtAmtPaid.Text = "" Then
MsgBox("Please fill-in Amount Paid by Customer", MsgBoxStyle.Information, "Validation")
txtAmtPaid.Focus()
Exit Sub
ElseIf cmdpayment.Text = "" Then
MsgBox("Please choose Payment status field", MsgBoxStyle.Information, "Validation")
cmdpayment.Focus()
Exit Sub
End If
saveitems()
'DecreaseStocksOnhand()
'UpdateToDecreaseStocksOnHand()
btnreceipt.Show()
getTransactionID()
' GenerateInvoiceNo()
dgw.Rows.Clear()
' btnreceipt.Show()
End Sub
Private Sub Deleteitem()
Try
Sql = "DELETE * FROM bills WHERE productID = '" & dgw.SelectedRows(0).Cells("productID").Value & "'"
ConnDB()
cmd = New SqlCommand(sqL, conn)
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Do While dr.Read = True
dgw.Rows.Add(dr(0), dr(1), dr(2), dr(3))
Loop
Catch ex As Exception
MsgBox(ex.Message)
Finally
cmd.Dispose()
conn.Close()
End Try
End Sub
Private Sub btnremove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnremove.Click
If MsgBox("Are you sure you want to remove this Product from Cart", MsgBoxStyle.YesNo, "Validation") = MsgBoxResult.Yes Then
Deleteitem()
loadbills()
gettotalitems()
totalamt()
clear()
txttotal.Text = ""
txtQuantity.Text = ""
End If
End Sub
Private Sub txtAmtPaid_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtAmtPaid.TextChanged
txtBalance.Text = Val(lblTotalAmount.Text) - Val(txtAmtPaid.Text)
End Sub
Private Sub cmdpayment_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdpayment.SelectedIndexChanged
If cmdpayment.SelectedIndex = 1 Then
txtAmtPaid.Text = "0"
End If
End Sub
Private Sub btnreceipt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnreceipt.Click
receipt.lblInvoice.Text = lblInvoice.Text
receipt.Show()
End Sub
End Class

Visual Studio 2010 - Message Box popping up twice, why and how to fix?

I'm writing a small app that allows the user to return and update three types of labels based on searching by charting number, order number, or product ID. How the design works is that there is an input box where you input the either the charting number/order number/product id and specify by selecting one of three radio buttons corresponding to the above three choices for input. There are three boxes to the right of the input box that returns the label IDs of each type of label, and the contents of these box can be directly edited and updated by clicking on an update button. The problem is that the return message pops up twice after updating, which is a nuisance, so I was wondering where in my code should I change to resolve this issue? I will paste the full code below in case the problem is located somewhere I haven't expected:
Imports MySql.Data.MySqlClient
Public Class Form1
Dim dbconn As New MySqlConnection
Dim sql As String
Dim mycommand As New MySqlCommand
Dim mydata As MySqlDataReader
Public Sub myConnection()
dbconn = New MySqlConnection("Server=###;Database=###;Uid=###;Pwd=###;")
Try
dbconn.Open()
Catch ex As Exception
MsgBox("Connection Error: " & ex.Message.ToString)
End Try
End Sub
Private Sub chartNoSub()
myConnection()
sql = "SELECT pltlbl, cuslbl, boxlbl from formats as a join ordtab as b join chart as c where a.prodid=b.cusled and concat(b.ordno, b.orditm)=concat(c.ord01, c.oitm01) and c.chart='" & inputBox.Text & "'"
mycommand.Connection = dbconn
mycommand.CommandText = sql
mydata = mycommand.ExecuteReader
While (mydata.Read())
pltLBL.Text = mydata.Item("pltlbl")
cusLBL.Text = mydata.Item("cuslbl")
boxLBL.Text = mydata.Item("boxlbl")
End While
mydata.Close()
dbconn.Close()
End Sub
Private Sub ordNoSub()
myConnection()
sql = "SELECT pltlbl, cuslbl, boxlbl from formats as a join ordtab as b where a.prodid=b.cusled and concat(b.ordno, '-', b.orditm)='" & inputBox.Text & "'"
mycommand.Connection = dbconn
mycommand.CommandText = sql
mydata = mycommand.ExecuteReader
While (mydata.Read())
pltLBL.Text = mydata.Item("pltlbl")
cusLBL.Text = mydata.Item("cuslbl")
boxLBL.Text = mydata.Item("boxlbl")
End While
mydata.Close()
dbconn.Close()
End Sub
Private Sub prodIDsub()
myConnection()
sql = "select pltlbl, cuslbl, boxlbl from formats where prodid='" & inputBox.Text & "'"
mycommand.Connection = dbconn
mycommand.CommandText = sql
mydata = mycommand.ExecuteReader
While (mydata.Read())
pltLBL.Text = mydata.Item("pltlbl")
cusLBL.Text = mydata.Item("cuslbl")
boxLBL.Text = mydata.Item("boxlbl")
End While
mydata.Close()
dbconn.Close()
End Sub
Private Sub Input_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles inputBox.TextChanged
pltLBL.Clear()
cusLBL.Clear()
boxLBL.Clear()
If (inputBox.Text <> "" And prodID.Checked = False And ordNo.Checked = False And chart.Checked = False) Then MsgBox("Please select an option below before inputting.")
If prodID.Checked = True Then
prodIDsub()
End If
If ordNo.Checked = True Then
ordNoSub()
End If
If chart.Checked = True Then
chartNoSub()
End If
End Sub
Private Sub update_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles updateLBL.Click, updateLBL.Click
myConnection()
sql = "update formats as a inner join ordtab as b on a.prodid = b.cusled inner join chart as c on b.ordno=c.ord01 and b.orditm=c.oitm01 set a.pltlbl = '" & pltLBL.Text & "', a.cuslbl = '" & cusLBL.Text & "', a.boxlbl = '" & boxLBL.Text & "' where a.prodid = '" & inputBox.Text & "' or concat(b.ordno, '-', b.orditm)='" & inputBox.Text & "' or c.chart='" & inputBox.Text & "'"
mycommand.Connection = dbconn
mycommand.CommandText = sql
mycommand.CommandType = CommandType.Text
Dim rows = mycommand.ExecuteNonQuery()
If rows <> 0 Then
MessageBox.Show("Update successful!")
Else
MessageBox.Show("Check input.")
End If
dbconn.Close()
End Sub
Private Sub clear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles clearLBL.Click
prodID.Checked = False
ordNo.Checked = False
chart.Checked = False
inputBox.Text() = ""
End Sub
End Class
Just to mark this as answered;
The solution was found, somewhat incredibly, by #GlorinOakenfoot.
The MsgBox was being called in Private Sub update_Click, but the Handles had the event happening twice on every click, hence the recursion of everything.

Identifier expected? visual basic

im almost done with this and then that... hopefully someone will be able to help me (Really hope so atleast, cus i need to be done with this:P) (need more text cus there is to much code):
|error is there|>
Private Sub FlatButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FlatButton1_Click. <|error is there|
Dim Conn As New MySqlConnection("Not going to publish this")
If FlatTextBox1.Text = "" Then
MsgBox("No username specified")
FlatTextBox2.Text = ""
Else
If FlatTextBox2.Text = "" Then
MsgBox("No password specified")
FlatTextBox1.Text = ""
Else
Try
Me.Text = "Logging in..."
Conn.Open()
Dim sqlquery As String = "SELECT * FROM Testing WHERE Username = '" & FlatTextBox1.Text & "';"
Dim data As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = sqlquery
command.Connection = Conn
adapter.SelectCommand = command
data = command.ExecuteReader
While data.Read()
If data.HasRows() = True Then
If data(2).ToString = FlatTextBox2.Text Then
Me.Text = "Logged in!"
My.Settings.Username = FlatTextBox1.Text
MsgBox("Welcome " + data(1).ToString)
Home.Show()
Me.Close()
If data(3).ToString = "1" Then
My.Settings.Admin = "Yes"
Else
My.Settings.Admin = "No"
End If
End If
Else
MsgBox("Failed Login")
End If
End While
Catch ex As Exception
End Try
End If
End If
End Sub
End Class
Replace these Lines
Private Sub FlatButton1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles FlatButton1_Click
With
Private Sub FlatButton1_Click(sender As Object, e As EventArgs) Handles FlatButton1_Click

Updating Datagridview?

I'm trying to figure out how to update a selected row in my DataGridView. I would like my system to recognize an existing row of information I've selected from my datagridview (I've set it to full row select btw) and update/edit the information by changing them with the textboxes and comboboxes I used to add them. Everything in my table is set as Text datatype, besides ID which is auto number. However, I get an error with the code I used below. Any help will be greatly appreciated! Thank you :) (I'm gonna provide a link to the screenshot of the error since I don't have enough reputation.)
* New error when I enclose Section with brackets
http://i.imgur.com/gs8rVhB.png
Imports System.Data.OleDb
Public Class AdmMain
Dim con As New OleDbConnection
Sub fillcombo()
strsql = " select yrgr from yearandgrade"
Dim acscmd As New OleDb.OleDbCommand
acscmd.CommandText = strsql
acscmd.Connection = acsconn
acsdr = acscmd.ExecuteReader
While (acsdr.Read())
cboyr.Items.Add(acsdr("yrgr"))
End While
acscmd.Dispose()
acsdr.Close()
End Sub
Sub comb2()
strsql = " select sections from sectio"
Dim acscmd As New OleDb.OleDbCommand
acscmd.CommandText = strsql
acscmd.Connection = acsconn
acsdr = acscmd.ExecuteReader
While (acsdr.Read())
cbosec.Items.Add(acsdr("sections"))
End While
acscmd.Dispose()
acsdr.Close()
End Sub
Private Sub LinkLabel1_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
If MessageBox.Show("Are you sure you want to logout?", "Logout", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
MessageBox.Show("You have successfully logged out of VCM's Library Information System!", "Logout Confirmed")
Me.Close()
LoginUser.Show()
End If
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Me.TxtID.Text = ""
Me.txtFName.Text = ""
Me.txtMName.Text = ""
Me.txtLName.Text = ""
Me.cboyr.Text = ""
Me.cbosec.Text = ""
Me.TxtID.Focus()
End Sub
Private Sub AdmMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Module1.connect()
Me.fillcombo()
Me.comb2()
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Thesis\Thesis\Database1.accdb"
con.Open()
datagridshow()
End Sub
Private Sub datagridshow()
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter
da = New OleDbDataAdapter("select * from students ", con)
da.Fill(dt)
DataGridView1.DataSource = dt.DefaultView
con.Close()
End Sub
Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
Dim rbdtext As String = cboyr.SelectedItem.ToString
Dim uno As String = cbosec.SelectedItem.ToString
Try
Dim cnString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Thesis\Thesis\Database1.accdb"
Dim sqlquery As String = "INSERT INTO students " & _
"(StudentID, FirstName,MiddleName,LastName,Yr, [Section]) " & _
"VALUES (#studid, #fname,#mname,#lname,#yr, #sec)"
' Use this form to initialize both connection and command to
' avoid forgetting to set the appropriate properties....
Using conn = New System.Data.OleDb.OleDbConnection(cnString)
Using cmd = New System.Data.OleDb.OleDbCommand(sqlquery, conn)
conn.Open()
cmd.Parameters.AddWithValue("#studid", TxtID.Text)
cmd.Parameters.AddWithValue("#fname", txtFName.Text)
cmd.Parameters.AddWithValue("#mname", txtMName.Text)
cmd.Parameters.AddWithValue("#lname", txtLName.Text)
cmd.Parameters.AddWithValue("#yr", rbdtext)
cmd.Parameters.AddWithValue("#sec", uno)
If TxtID.Text = "" Or txtFName.Text = "" Or txtMName.Text = "" Or txtLName.Text = "" Or cboyr.SelectedIndex = -1 Or cbosec.SelectedIndex = -1 Then
MessageBox.Show("Please complete the required fields.", "Admin", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Return
Else
Dim rowsInserted = cmd.ExecuteNonQuery()
If rowsInserted > 0 Then
MessageBox.Show("One record successfully added!", "Added!")
datagridshow()
Else
MessageBox.Show("Failure to add new record!", "Failure!")
End If
End If
End Using
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub TxtID_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TxtID.KeyPress
'97 - 122 = Ascii codes for simple letters
'65 - 90 = Ascii codes for capital letters
'48 - 57 = Ascii codes for numbers
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
End Sub
Private Sub btnEdit_Click(sender As System.Object, e As System.EventArgs) Handles btnEdit.Click
Dim rbdtext As String = cboyr.SelectedItem.ToString
Dim uno As String = cbosec.SelectedItem.ToString
Try
Dim cnString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Thesis\Thesis\Database1.accdb"
Dim sqlquery As String = "UPDATE Students SET StudentID = #STUDID, FirstName = #FNAME, MiddleName = #MNAME, LastName= #LNAME, Yr = #YRR, [Section] = #SEC WHERE StudentID = #STUDID, FirstName =#FNAME, MiddleName = #MNAME, LastName= #LNAME, Yr = #YRR, [Section] = #SEC"
' Use this form to initialize both connection and command to
' avoid forgetting to set the appropriate properties....
Using conn = New System.Data.OleDb.OleDbConnection(cnString)
Using cmd = New System.Data.OleDb.OleDbCommand(sqlquery, conn)
conn.Open()
cmd.Parameters.AddWithValue("#STUDID", TxtID.Text)
cmd.Parameters.AddWithValue("#FNAME", txtFName.Text)
cmd.Parameters.AddWithValue("#MNAME", txtMName.Text)
cmd.Parameters.AddWithValue("#LNAME", txtLName.Text)
cmd.Parameters.AddWithValue("#YRR", rbdtext)
cmd.Parameters.AddWithValue("#SEC", uno)
If TxtID.Text = "" Or txtFName.Text = "" Or txtMName.Text = "" Or txtLName.Text = "" Or cboyr.SelectedIndex = -1 Or cbosec.SelectedIndex = -1 Then
MessageBox.Show("Please complete the required fields.", "Admin", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Return
Else
Dim rowsInserted = cmd.ExecuteNonQuery()
If rowsInserted > 0 Then
MessageBox.Show("One record successfully updated!", "Updated!")
datagridshow()
Else
MessageBox.Show("Failure to update new record!", "Failure!")
End If
End If
End Using
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
The syntax of a UPDATE...WHERE expression requires a condition that uniquely identifies the record to UPDATE. If the condition is an expression composed of more than one field/value then these conditions should be combined using AND or OR operators not using commas.
Usually the condition in the WHERE clause identifies the record to be updated using the PRIMARY KEY of the table (in your case this seems to be the StudentID field) so you just need to write
Dim sqlquery As String = "UPDATE Students SET FirstName = #FNAME, " &_
"MiddleName = #MNAME, LastName= #LNAME, Yr = #YRR, " & _
"[Section] = #SEC " & _
"WHERE StudentID = #STUDID"
Note that if StudentID is the PRIMARYKEY you don't try to change/update it bacause this could cause inconsistencies in your other database tables that refer (have a relationship) with the Students table
Finally, the OleDb provider don't recognize the parameter by their name, the provider expects that each parameter passed is in the same order in which the parameter placeholders appears in the command text (It use the position of the parameter to pass the value to the database engine), so you need to change also the order in which you set up the parameter collection for the UPDATE
cmd.Parameters.AddWithValue("#FNAME", txtFName.Text)
cmd.Parameters.AddWithValue("#MNAME", txtMName.Text)
cmd.Parameters.AddWithValue("#LNAME", txtLName.Text)
cmd.Parameters.AddWithValue("#YRR", rbdtext)
cmd.Parameters.AddWithValue("#SEC", uno)
cmd.Parameters.AddWithValue("#STUDID", TxtID.Text)

How to insert, edit, delete image in SQL using vb.net

I can't Search and Edit using this Code. Insert is working. But Insert coding method is not sure (fileContent.ToString). And Search part and Update part is not working.
Dim fileContent As Byte() = My.Computer.FileSystem.ReadAllBytes(OpenFileDialog1.FileName)
Sub NormalUpdate(ByVal _Query)
con.Open()
Dim cmdUpdate As New SqlCommand(_Query)
cmdUpdate.Connection = con
cmdUpdate.CommandType = CommandType.Text
cmdUpdate.ExecuteNonQuery()
con.Close()
End Sub
Sub NormalSave(ByVal _Query)
con.Open()
Dim cmdSave As New SqlCommand(_Query)
cmdSave.Connection = con
cmdSave.CommandType = CommandType.Text
cmdSave.ExecuteNonQuery()
con.Close()
End Sub
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
NormalSave("Insert into Registration values('" + txtMemberNo.Text + "','" + fileContent.ToString + "')")
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
con.Open()
Using cmd As New SqlClient.SqlCommand("Select MemberPicture From Registration where MemberNo = '" + txtMemberNo.Text + "'", con)
Using dr As SqlClient.SqlDataReader = cmd.ExecuteReader()
Using dt As New DataTable
dt.Load(dr)
Dim row As DataRow = dt.Rows(0)
Using ms As New IO.MemoryStream(CType(row("MemberPicture"), Byte()))
Dim img As Image = Image.FromStream(ms)
ProfilePic.Image = img
con.Close()
End Using
End Using
End Using
End Using
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
NormalUpdate("Update Registration set MemberPicture = '" + fileContent.ToString + "' where MemberNo = '" + txtMemberNo.Text + "'")
End Sub
Please help me. Thanks.
Not sure if this is what you are looking for, but I use the following to get and set images from a database:
Public Function GetClientImage(ID As String) As Image
Dim ClientPicture As Image = Nothing
Dim DS As DataSet = Nothing
'Populate DS here
If (DS IsNot Nothing) AndAlso (DS.Tables.Count > 0) AndAlso (DS.Tables(0).Rows.Count > 0) Then
Dim DR As DataRow = DS.Tables(0).Rows(0)
Try
Dim Pic As Object = DR!Picture
If Pic IsNot DBNull.Value Then
Dim Buffer As Byte() = CType(DR!Picture, Byte())
If Buffer IsNot Nothing AndAlso (Buffer.Length > 0) Then
Using MS As New IO.MemoryStream(Buffer, 0, Buffer.Length)
MS.Write(Buffer, 0, Buffer.Length)
ClientPicture = Image.FromStream(MS, True)
End Using
End If
End If
Catch ex As Exception
MessageBox.Show("Error retrieving Image: " & ControlChars.NewLine & ControlChars.NewLine & ex.ToString, My.Application.Info.AssemblyName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
End Try
End If
Return ClientPicture
End Function
and:
Public Function UpdateClientImage(ID As String, Pic As Image) As Integer
Dim Result As Integer = 0
If Client IsNot Nothing Then
Dim SQL As String = "UPDATE Clients SET Picture = #photo WHERE ID = '" & ID & "' ;"
Using SQLConn As New SqlClient.SqlConnection(ConnectionString)
Try
SQLConn.Open()
Using SQLCmd As New SqlClient.SqlCommand(SQL, SQLConn)
Dim PhotoParameter As New SqlClient.SqlParameter("#photo", SqlDbType.Image)
Dim MS As New IO.MemoryStream()
If Pic IsNot Nothing Then
Pic.Save(MS, Imaging.ImageFormat.Bmp)
End If
PhotoParameter.SqlValue = MS.GetBuffer
SQLCmd.Parameters.Add(PhotoParameter)
Result = SQLCmd.ExecuteNonQuery()
End Using
Catch ex As Exception
Dim Msg As String = "Unable to save Client's Picture"
If ex IsNot Nothing Then
Msg &= ":" & ControlChars.NewLine & ControlChars.NewLine & ex.ToString
End If
MessageBox.Show(Msg, My.Application.Info.AssemblyName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
Finally
If Not SQLConn.State = ConnectionState.Closed Then
SQLConn.Close()
End If
End Try
End Using
End If
Return Result
End Function
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles
Dim OpennFileDialog As OpenFileDialog
query = "update tblEmployeeSetup set dbImage = #dbImage where empy_id = '" + txtEmpId.Text + "' "
insertImage(query, "Data Saved...", lblSave, OpennFileDialog )
End Sub
Sub insertImage(ByVal query As String, ByVal message As String, ByVal lblSave As Label, ByVal a As OpenFileDialog)
Try
If con.State = ConnectionState.Closed Then
con.Open()
End If
' Dim result As DialogResult = a.ShowDialog()
' a.FileName = My.Resources.DefultImage.ToString
cmd.Connection = con
cmd.CommandText = query
cmd.Parameters.Add(New SqlClient.SqlParameter("#dbimage", SqlDbType.Image)).Value = IO.File.ReadAllBytes(a.FileName)
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
lblSave.Text = message
a.Dispose()
Catch ex As Exception
MessageBox.Show("Error" & ex.Message)
Finally
con.Close()
End Try
End Sub