VB.NET SQL Update Table Using Listbox As Identifier - sql

Hi I'm just learning how handle SQL statements using vb.net. My problem is how do I update my table using the items in listbox as an identifier.
My SQL query is working.
update tblBillingSched set Status = 'paid'
where BillNum = 'MA5'
Here's the revised code:
Private Sub btnPostAdvancedPayment_Click(sender As Object, e As EventArgs) Handles btnPostAdvancedPayment.Click
Dim connection_string As String = "Data Source=.\sqlexpress;Initial Catalog=CreditAndCollection;Integrated Security=True"
Dim connection As New SqlConnection(connection_string)
connection.Open()
Dim SQLCmd As SqlCommand
Dim sSQL As String = "UPDATE tblBillingSched SET Status = 'Paid' WHERE BillNum = "
If MessageBox.Show("Continue to Save?", " ", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then
Dim firstTime As Boolean = True
For Each item In lstBillNum.Items
If (item IsNot Nothing AndAlso item.ToString().Trim().Length > 0) Then
If (firstTime) Then
firstTime = False
Else
sSQL = sSQL & " OR BillNum = "
End If
sSQL = sSQL & "'" & item.ToString() & "'"
End If
Next
SQLCmd = New SqlCommand(sSQL, Connection)
SQLCmd.ExecuteNonQuery()
MessageBox.Show("Client Record Successfully Saved!", " ", MessageBoxButtons.OK, MessageBoxIcon.Information)
connection.Close()
SQLCmd.Dispose()
ElseIf DialogResult.Cancel Then
MessageBox.Show("Saving Cancelled!", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim dt as date = CDate(DateTime.Today).ToString("MM/dd/yyyy")
Try
Dim cn As New OleDb.OleDbConnection
cn.ConnectionString = GetConnectionStringByName("FD_project.My.MySettings.fixedepoConnectionString")
Dim sSQL As String = "UPDATE fixdeporeg SET approval = 'A', a_user = 'CFO', " & _
"app_date = # " & dt & "# WHERE slno = "
If MessageBox.Show("Continue to Save?", " ", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then
Dim firstTime As Boolean = True
For x As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
If (firstTime) Then
firstTime = False
Else
sSQL = sSQL & " OR slno = "
End If
'sSQL = sSQL & "'" & item.ToString() & "'"
sSQL = sSQL & CheckedListBox1.CheckedItems(x).item("slno")
Next
Dim SQLCmd As OleDbCommand = New OleDbCommand(sSQL, cn)
MessageBox.Show(sSQL)
cn.Open()
'dt = cmd1.ExecuteScalar()
SQLCmd.ExecuteNonQuery()
cn.Close()
ElseIf DialogResult.Cancel Then
MessageBox.Show("Saving Cancelled!", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub

I understand that you are after a loop on these lines:
Dim sSQL As String = "UPDATE tblBillingSched SET Status = 'paid' WHERE BillNum = "
Dim firstTime As Boolean = True
For Each item In lstBillNum.Items
If (item IsNot Nothing AndAlso item.ToString().Trim().Length > 0) Then
If (firstTime) Then
firstTime = False
Else
sSQL = sSQL & " OR BillNum = "
End If
sSQL = sSQL & "'" & item.ToString() & "'"
End If
Next

Related

This is error message "Could not save; currently locked by another user."

Can you help you find to any solution? Because it's output error message as "Could not save; currently locked by another user."
Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
If txtPassword.Text.ToString() = "" Then
MsgBox("do not empty")
ElseIf txtUsername.Text.ToString() = "" Then
MsgBox("do not empty")
ElseIf txtSurName.Text.ToString() = "" Then
MsgBox("do not empty")
ElseIf txtGivenName.Text.ToString() = "" Then
MsgBox("do not empty")
ElseIf txtMobile.Text.ToString() = "" Then
MsgBox("do not empty")
ElseIf txtAddress.Text.ToString() = "" Then
MsgBox("do not empty")
ElseIf txtIC.Text.ToString() = "" Then
MsgBox("do not empty")
Else
Dim gender As String
If RadioButton1.Checked = True Then
gender = "Male"
Else
gender = "Female"
End If
Dim fsr As New FileStream(OpenFileDialog1.FileName, FileMode.Open, FileAccess.Read)
Dim br As New BinaryReader(fsr)
Dim imgbuffer(fsr.Length) As Byte
br.Read(imgbuffer, 0, fsr.Length)
fsr.Close()
Using con As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source =..\VisitorPass.accdb")
con.Open()
Dim sql As String
sql = "Update HouseOwner set [Password]='" & txtPassword.Text & "',AccountName='" & txtUsername.Text & "',Houseowner_Surname='" & txtSurName.Text & "',Houseowner_GivenName='" & txtGivenName.Text & "',[IC]='" & txtIC.Text & "',[Mobile_No]='" & txtMobile.Text & "',Houseowner_address='" & txtAddress.Text & "',Gender='" & gender & "',[Photo]= #imgfile where [ID]=" & lblID.Text & ""
Using cmd As New OleDbCommand(sql, con)
cmd.Parameters.AddWithValue("#imgfile", imgbuffer)
cmd.ExecuteNonQuery()
MsgBox("Profile is updated")
con.Close()
End Using
End Using
Me.Close()
End If
End Sub

vb.net Read and write data to ms database using Odbc(ERROR)

When I try to run the program, an error shows " ERROR[07002][Microsoft][ODBC MICROSOFT ACCESS DRIVER] TOO FEW PARAMETERS.EXPECTED 1" USING THIS CONNECTION.
Public Sub open_connection ()
Try
con = New OdbcConnection("dsn = LocalDB")
con.Open()
End try
Catch ex As Exception
MsgBox(ex.message)
End sub
Problems occurs when inserting and reading..
sSql = "select * from Faculty where RFID='" & txtrfid.Text & "'"
Dim cmd As New OdbcCommand(sSql, con)
Dim dr As OdbcDataReader = cmd.ExecuteReader()
If dr.HasRows Then
dr.Read()
txtfname.Text = dr("fname").ToString()
txtlname.Text = dr("lname").ToString()
txtid.Text = dr("STID").ToString()
txtposition.Text = dr("Pstion").ToString()
txtsubject.Text = dr("Subject").ToString()
Dim bits As Byte() = CType(dr("Pfile"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
imgRetrieve.Image = myimg
dr.Close()
sSql = " SELECT TOP 1 flag_inout FROM Attendance where faculty_id = #StId ORDER BY Attendance_id DESC"
Dim pcmd As New OdbcCommand(sSql, con)
pcmd.Parameters.AddWithValue("#StId", txtid.Text)
Dim pdr As OdbcDataReader = pcmd.ExecuteReader()
While pdr.Read()
TextBox1.Text = pdr("flag_inout").ToString()
End While
If TextBox1.Text = "IN" Then
TextBox1.Text = "OUT"
ElseIf TextBox1.Text = "OUT" Then
TextBox1.Text = "IN"
ElseIf TextBox1.Text = Nothing Then
TextBox1.Text = "IN"
End If
pdr.Close()
'Check Duplicate
'If txtfname.Text.Length = 0 Then
' Return
'End If
'If Not CheckDateDuplicate() Then
' MessageBox.Show("Already Saved on this Date")
' Return
'End If
sSql = "insert into Attendance (faculty_id, faculty_Fname,faculty_Lname,[Position],Subject, attendance_date, attendance_time, flag_inout) values('" & txtid.Text & "','" & txtfname.Text & "','" & txtlname.Text & "','" & txtposition.Text & "','" & txtsubject.Text & "','" & DateTimePicker1.Value.Date & "','" & TimeOfDay.ToShortTimeString & "','" & TextBox1.Text & "')"
Dim xcmd As New OdbcCommand(sSql, con)
If xcmd.ExecuteNonQuery() > 0 Then
'MessageBox.Show("ATTENDANCE SAVED")
txtrfid.Text = ""
'txtid.Text = ""
'txtfname.Text = ""
'txtlname.Text = ""
'txtposition.Text = ""
'txtsubject.Text = ""
txtrfid.Focus()
Dtagrid()
End If
If TextBox1.Text = "IN" Then
lblinuse.Visible = True
lblvacant.Visible = False
lbllstuser.Visible = False
lblcrrntuser.Visible = True
ElseIf TextBox1.Text = "OUT" Then
lblinuse.Visible = False
lblvacant.Visible = True
lbllstuser.Visible = True
lblcrrntuser.Visible = False
'txtid.Text = ""
'txtfname.Text = ""
'txtlname.Text = ""
'txtposition.Text = ""
'txtsubject.Text = ""
'imgRetrieve.Image = Nothing
End If
End If
Dtagrid()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
CAUSE
This error occurs only with Microsoft Access when one of the column
names specified in a select statement does not exist in the table
being queried.
Resolution
Remove any invalid column names from the select statement.
Make sure that Column Name RFID exist in Faculty table and also check txtrfid has value or not

VB.NET search stucks with MS Access

When I try to make another search order the program gets stuck.
I mean I can make one search operation, but then program stops working.
This is my code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Static m As Integer = 0
If TextBox1.Text = Trim("") Then Exit Sub
If RadioButton4.Checked = True Then
ExactSearch()
ElseIf RadioButton5.Checked = True Then
GeneralSearch()
End If
Conn.Open()
Dim DataAdapter1 As New OleDbDataAdapter(SQLstr, Conn)
DataAdapter1.Fill(DataSet1, "Table1")
Conn.Close()
TextBox2.DataBindings.Add("Text", DataSet1, "Table1.Name")
TextBox3.DataBindings.Add("Text", DataSet1, "Table1.DatTim")
TextBox4.DataBindings.Add("Text", DataSet1, "Table1.mobile")
DataGridView1.DataSource = DataSet1
DataGridView1.DataMember = "Table1"
'Button1.Enabled = False
If Me.BindingContext(DataSet1, "Table1").Count = 0 Then
MsgBox("No Result, Please Try Again ")
Exit Sub
End If
Button2.Enabled = True
Button3.Enabled = True
End Sub
Public Sub ExactSearch()
If RadioButton1.Checked = True Then
SQLstr = "SELECT * FROM Table1 WHERE name = '" & TextBox1.Text & "'"
ElseIf RadioButton2.Checked = True Then
SQLstr = "SELECT * FROM Table1 WHERE DatTim = '" & TextBox1.Text & "'"
ElseIf RadioButton3.Checked = True Then
SQLstr = "SELECT * FROM Table1 WHERE mobile = '" & TextBox1.Text & "'"
End If
End Sub
Public Sub GeneralSearch()
If RadioButton1.Checked = True Then
SQLstr = "SELECT * FROM Table1 WHERE name LIKE '%" & TextBox1.Text & "%'"
ElseIf RadioButton2.Checked = True Then
SQLstr = "SELECT * FROM Table1 WHERE DatTim LIKE '%" & TextBox1.Text & "%'"
ElseIf RadioButton3.Checked = True Then
SQLstr = "SELECT * FROM Table1 WHERE mobile LIKE '%" & TextBox1.Text & "%'"
End If
End Sub
It gets stuck here
TextBox2.DataBindings.Add("Text", DataSet1, "Table1.Name")
Please help.
When
DataAdapter1.Fill(DataSet1, "Table1")
Then
TextBox2.DataBindings.Add("Text", DataSet1.Tables("Table1"), "Name")

vbnet multiple combobox fill with one dataset

i have the following code to fill two comboboxes using one dataset:
Private Sub sub_cbo_type_load()
Dim ds As New DataSet
ds = cls.cbo_type()
If ds IsNot Nothing _
AndAlso ds.Tables.Count > 0 _
AndAlso ds.Tables(0).Rows.Count > 0 Then
Me.r_cbo_type.DataSource = ds.Tables(0)
Me.r_cbo_type.DisplayMember = "desc"
Me.r_cbo_type.ValueMember = "code"
Me.r_cbo_type.SelectedIndex = -1
Me.m_cbo_type.DataSource = ds.Tables(0)
Me.m_cbo_type.DisplayMember = "desc"
Me.m_cbo_type.ValueMember = "code"
Me.m_cbo_type.SelectedIndex = -1
End If
End Sub
the problems is: whenever the index is changed in one combobox, it's automatically changed in the other one too.
does anyone know how can i solve this?
thanks for your time.
Try cloning the tables:
Private Function CopyTable(ByVal sourceTable As DataTable) As DataTable
Dim newTable As DataTable = sourceTable.Clone
For Each row As DataRow In sourceTable.Rows
newTable.ImportRow(row)
Next
Return newTable
End Function
Then your data sources would be referencing different sources:
Me.r_cbo_type.DataSource = CopyTable(ds.Tables(0))
Me.m_cbo_type.DataSource = CopyTable(ds.Tables(0))
do like this
Private Sub btn_update1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_update1.Click
If MsgBox("Are you sure to update?" & "", MsgBoxStyle.YesNo, "Confirmation") = MsgBoxResult.Yes = True Then
Dim transmode As String = vbNullString
Dim byair As String = vbNullString
Dim bysea As String = vbNullString
If rb_air.Checked = True Then
transmode = "A"
byair = txt_mserial.Text '.Substring(txt_mserial.TextLength - 4, 4)
bysea = vbNullString
ElseIf rb_sea.Checked = True Then
transmode = "B"
byair = vbNullString
bysea = txt_mserial.Text '.Substring(txt_mserial.TextLength - 4, 4)
End If
Try
If con.State = ConnectionState.Closed Then con.Open()
global_command = New SqlCommand("update ytmi_finished_products set rev_ctrl_no = '" & txt_mrev.Text & "', by_air = '" & byair & "', by_sea = '" & bysea & "', transport_mode = '" & transmode & "' where REPLACE(prod_no, '-', '') +'-'+ ISNULL(CONVERT(varchar(50), prod_sx), '') + prod_lvl = '" & txt_mpart.Text & "' and cast(serial_no as numeric) = '" & txt_mserial.Text & "' and req_box_qty = '" & txt_mqty.Text & "' and remarks is null", con)
global_command.ExecuteNonQuery()
global_command.Dispose()
MsgBox("Successfully Updated!", MsgBoxStyle.Information, "Message")
mclear()
Catch ex As Exception
MsgBox("Trace No 20: System Error or Data Error!" + Chr(13) + ex.Message + Chr(13) + "Please Contact Your System Administrator!", vbInformation, "Message")
End Try
End If
End Sub

How to convert this String-based sql query to use Linq

I have the following routine (that works) but which is messy to update owing to the hand-typed strings it uses:
Private Sub ListDefaults()
Dim conn As New SqlConnection( _
"server=bas047\AUTODESKVAULT;Database=DWGDetails;Integrated Security=SSPI")
'Dim conn As New SqlConnection( _
'"server=bas047\AUTODESKVAULT;Database=DWGDetails;Integrated Security=SSPI")
Try
'clear columns
If Not Me.DataGridView1.DataSource Is Nothing Then
Me.DataGridView1.Columns.Clear()
Me.DataGridView1.DataSource = Nothing
End If
conn.Open()
Dim cmd As SqlCommand = conn.CreateCommand()
Dim DLcmd As SqlCommand = conn.CreateCommand()
Dim ILcmd As SqlCommand = conn.CreateCommand()
'Dim srctbl As String = String.Empty
If RadioButton1.Checked = True Then 'A3
shtsize = "A3"
cmd.CommandText = "SELECT [AttributeName],[IsDefaultValue],[DefaultValue] FROM " & _
Chr(34) & "DefaultValues(Borders SB-A3_993-5.2(block))" & Chr(34)
srctbl = "DefaultValues(Borders SB-A3_993-5.2(block))"
ElseIf RadioButton2.Checked = True Then 'A2
shtsize = "A2"
cmd.CommandText = "SELECT [AttributeName],[IsDefaultValue],[DefaultValue] FROM " & _
Chr(34) & "DefaultValues(Borders SB-A2_992-5.2(block))" & Chr(34)
srctbl = "DefaultValues(Borders SB-A2_992-5.2(block))"
ElseIf RadioButton3.Checked = True Then 'A1
shtsize = "A1"
cmd.CommandText = "SELECT [AttributeName],[IsDefaultValue],[DefaultValue] FROM " & _
Chr(34) & "DefaultValues(Borders SB-A1_991-5.2(block))" & Chr(34)
srctbl = "DefaultValues(Borders SB-A1_991-5.2(block))"
ElseIf RadioButton4.Checked = True Then 'A0
shtsize = "A0"
cmd.CommandText = "SELECT [AttributeName],[IsDefaultValue],[DefaultValue] FROM " & _
Chr(34) & "DefaultValues(Borders SB-A0_990-5.2(block))" & Chr(34)
srctbl = "DefaultValues(Borders SB-A0_990-5.2(block))"
End If
'Populate datagridview1
da = New SqlDataAdapter(cmd.CommandText, conn.ConnectionString)
ds = New DataSet
da.Fill(ds, srctbl)
DataGridView1.DataSource = ds.Tables(0)
DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells)
'should enable setting of the date and drawn by entries
'Dim X As Integer
'For X = 0 To DataGridView1.Rows.Count
' If UCase(DataGridView1.Rows(X).Cells(0).Value) = "DRAWN BY" Then
' MessageBox.Show("Found Drawn by!")
' End If
'Next
Catch ex As System.Data.SqlClient.SqlException
MessageBox.Show("There was an error in executing the SQL." & vbLf & "Error Message:" & ex.Message, "SQL")
Finally
'cleanup and reset!
conn.Close()
End Try
End Sub
And I am thinking this is an ideal candidate for Linq. This is what I have so far that seems to work:
Private Sub ListDefaultsMk1()
Try
Using db As New DWGDetailsDataContext
If RadioButton1.Checked = True Then 'A3
shtsize = "A3"
DataGridView1.DataSource =
From c In db.DefaultValues_Borders_SB_A3_993_5_2_block__s()
Select New With {c.AttributeName, c.IsDefaultValue, c.DefaultValue}
ElseIf RadioButton2.Checked = True Then 'A2
shtsize = "A2"
DataGridView1.DataSource =
From c In db.DefaultValues_Borders_SB_A2_992_5_2_block__s()
Select New With {c.AttributeName, c.IsDefaultValue, c.DefaultValue}
ElseIf RadioButton3.Checked = True Then 'A1
shtsize = "A1"
DataGridView1.DataSource =
From c In db.DefaultValues_Borders_SB_A1_991_5_2_block__s()
Select New With {c.AttributeName, c.IsDefaultValue, c.DefaultValue}
ElseIf RadioButton4.Checked = True Then 'A0
shtsize = "A0"
DataGridView1.DataSource =
From c In db.DefaultValues_Borders_SB_A0_990_5_2_block__s()
Select New With {c.AttributeName, c.IsDefaultValue, c.DefaultValue}
End If
End Using
Catch ex As Exception
MessageBox.Show("There was an error in executing the SQL." & vbLf & "Error Message:" & ex.Message, "SQL")
End Try
End Sub
The next step of my program is to take the (edited) values from the datagridview (In the case of the handwritten SQL code, the shared DataSet "ds") and populate another table but I can't figure out how to do that using Linq.
Can anyone offer assistance?
Thanks in advance,
Alex.
EDIT: Here's what I've reduced it to based on the comment
Private Sub ListDefaultsMk1()
Try
Using db As New DWGDetailsDataContext
If RadioButton1.Checked = True Then 'A3
shtsize = "A3"
DataGridView1.DataSource = (From c In db.DefaultValues_Borders_SB_A3_993_5_2_block__s Select c).ToList()
ElseIf RadioButton2.Checked = True Then 'A2
shtsize = "A2"
DataGridView1.DataSource = (From c In db.DefaultValues_Borders_SB_A2_992_5_2_block__s Select c).ToList()
ElseIf RadioButton3.Checked = True Then 'A1
shtsize = "A1"
DataGridView1.DataSource = (From c In db.DefaultValues_Borders_SB_A1_991_5_2_block__s Select c).ToList()
ElseIf RadioButton4.Checked = True Then 'A0
shtsize = "A0"
DataGridView1.DataSource = (From c In db.DefaultValues_Borders_SB_A0_990_5_2_block__s Select c).ToList()
End If
End Using
Catch ex As Exception
MessageBox.Show("There was an error in executing the Linq2SQL Query!" & vbLf & "Error Message:" & ex.Message, "SQL")
End Try
End Sub
Linq2Sql and DataSets are two completely different beasts and the reason you can both use them in a grid is because the grid can consume more types than just dataset.
You could technically pin down the linq query result using, say, ToList() and then bind the List to a grid. Afterwards all edits will be reflected on List which you can transform into other formats as you feel like (you didn't give much information about where the data should go other than its a table, table in dataset (must it be dataset), table in database, etc).