Updated code. I think its close but the dgv doesn't load with any data.
Public Class CloseJob
Public sqlcon As String = My.Settings.New_Assembly_AccessConnectionString
Public con As New SqlConnection(sqlcon)
Public job As String
Public Async Function GetDataAsync(ByVal sql As String, ByVal sqlcon As String) As Task(Of DataTable)
Dim dt As New DataTable
Dim cmd As New SqlCommand(sql, con)
Using da = New SqlDataAdapter(sql, sqlcon)
da.SelectCommand = cmd
cmd.Parameters.AddWithValue("#Job2", job)
Await Task.Run(Function()
da.Fill(dt)
End Function)
End Using
Return dt
End Function
Public Async Sub Button_Click(sender As Object, e As RoutedEventArgs)
Refresh.Visibility = Windows.Visibility.Visible
txtJob.IsEnabled = False
btnEnter.IsEnabled = False
Try
job = txtJob.Text
Dim sqlcon As String = My.Settings.New_Assembly_AccessConnectionString
Dim sql As String
sql = "SELECT isnull(p.[CLASS],j.class) as 'CLASS',isnull([SERIAL_NUMBER],left(year(d.cup_mfg_date),2) + d.cup_serial) as SERIAL, " & _
"isnull([CUP_DATE],d.cup_mfg_date) as CUPDATE, isnull([CUP_PART_NUM],left([Cup#],charindex('-',Cup#)-1)) as PARTNUM, isnull(p.[LATERAL_VALUE], " & _
"d.lateral_value * 10000) as LATVALUE, isnull([LAT_UPPER],0) as LAT_UPPER,isnull([LAT_LOWER],0) as LAT_LOWER, " & _
"isnull(p.[BEFORE_WEIGHT],0) as BEFORE_WEIGHT, isnull(p.[AFTER_WEIGHT],0) as AFTER_WEIGHT,isnull([GREASE_UPPER],0) as GREASE_UPPER, " & _
"isnull([GREASE_LOWER],0) as GREASE_LOWER,isnull(p.[SPACER_MEASURE], d.Spacer_Measure) as SPACER,isnull([QTY_SPACER_CHANGE],0) as 'CHANGES', " & _
"isnull([LATERAL_DATE_TIME],'1999-11-11 11:11:11.111') as LATERAL_DATE_TIME, " & _
"isnull([GREASE_DATE_TIME],'1999-11-11 11:11:11.111') as GREASE_DATE_TIME, isnull([LINE_NUM],d.linenum) as LINE, " & _
"isnull(BAD_PART, 'BAD_INFO') as Result, isnull([AIR_PRESSURE1], 0) as PRESSURE " & _
"FROM [NB_ASSEMBLY].[dbo].[PieceData] p full outer JOIN New_Assembly_Access.dbo.Tbl_Data AS d " & _
"ON substring(d.zbarcode,3,6) = right(p.serial_number,6) and month(d.cup_mfg_date) = month(p.cup_date) and " & _
"right(d.zbarcode,10) = right(p.cup_part_num,10) join new_assembly_Access.dbo.tbl_job j on j.job# = d.job# where d.job# = #Job2"
con.Open()
Dim data = Await GetDataAsync(sql, sqlcon)
dgvJob.DataContext = data
dgvJob.AutoGenerateColumns = True
dgvJob.CanUserAddRows = False
Catch ex As Exception
End Try
Refresh.Visibility = Windows.Visibility.Hidden
End Sub
Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
Refresh.Visibility = Windows.Visibility.Hidden
txtJob.Focus()
End Sub
End Class
I recommend you clean your code up a bit and make methods that only do one thing - don't have a ReadDatabase that also fiddles with controls etc
DataAdapter can take a sql string and a connection string, it knows how to make a connection and open it etc. It tidies things up to hand all that off to the DA
And maybe put that massive SQL string into a Resources file
Private Async Function GetComponentsDataTable() as Task(Of DataTable)
Dim con As String = My.Settings.New_Assembly_AccessConnectionString
Dim sql as String = "SELECT isnull(p.[CLASS],j.class) as 'CLASS',isnull([SERIAL_NUMBER],left(year(d.cup_mfg_date),2) + d.cup_serial) as SERIAL, " & _
"isnull([CUP_DATE],d.cup_mfg_date) as CUPDATE, isnull([CUP_PART_NUM],left([Cup#],charindex('-',Cup#)-1)) as PARTNUM, isnull(p.[LATERAL_VALUE], " & _
"d.lateral_value * 10000) as LATVALUE, isnull([LAT_UPPER],0) as LAT_UPPER,isnull([LAT_LOWER],0) as LAT_LOWER, " & _
"isnull(p.[BEFORE_WEIGHT],0) as BEFORE_WEIGHT, isnull(p.[AFTER_WEIGHT],0) as AFTER_WEIGHT,isnull([GREASE_UPPER],0) as GREASE_UPPER, " & _
"isnull([GREASE_LOWER],0) as GREASE_LOWER,isnull(p.[SPACER_MEASURE], d.Spacer_Measure) as SPACER,isnull([QTY_SPACER_CHANGE],0) as 'CHANGES', " & _
"isnull([LATERAL_DATE_TIME],'1999-11-11 11:11:11.111') as LATERAL_DATE_TIME, " & _
"isnull([GREASE_DATE_TIME],'1999-11-11 11:11:11.111') as GREASE_DATE_TIME, isnull([LINE_NUM],d.linenum) as LINE, " & _
"isnull(BAD_PART, 'BAD_INFO') as Result, isnull([AIR_PRESSURE1], 0) as PRESSURE " & _
"FROM [NB_ASSEMBLY].[dbo].[PieceData] p full outer JOIN New_Assembly_Access.dbo.Tbl_Data AS d " & _
"ON substring(d.zbarcode,3,6) = right(p.serial_number,6) and month(d.cup_mfg_date) = month(p.cup_date) and " & _
"right(d.zbarcode,10) = right(p.cup_part_num,10) join new_assembly_Access.dbo.tbl_job j on j.job# = d.job# where d.job# = #Job2"
Using da as New SqlDataAdapter(sql, con)
da.SelectCommand.Parameters.AddWithValue("#Job2", job) 'see https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/'
Dim dt As New DataTable
Await Task.Run(Sub() da.Fill(dt)) 'also, see note from AlexB
Return dt
End Using
End Sub
Public Async Sub Button_Click(sender As Object, e As RoutedEventArgs)
txtJob.IsEnabled = False
btnEnter.IsEnabled = False
Dim dt = Await GetComponentsDataTable()
dgvJob.AutoGenerateColumns = True
dgvJob.DataContext = dt.DefaultView
dgvJob.CanUserAddRows = False
End Sub
Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
txtJob.Focus()
End Sub
This is your code modified on the fly, start from here as I don’t know if works well or if there needs changes without your database and other parameters.
Public con As New SqlConnection
Public job As String
Private Sub ReadDatabase()
Dim bgThread As Threading.Thread = New Threading.Thread(Sub()
Dim sqlcon As String = My.Settings.New_Assembly_AccessConnectionString
Dim sql As New SqlCommand
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Using con = New SqlConnection(sqlcon)
con.Open()
sql = New SqlCommand("SELECT isnull(p.[CLASS],j.class) as 'CLASS',isnull([SERIAL_NUMBER],left(year(d.cup_mfg_date),2) + d.cup_serial) as SERIAL, " &
"isnull([CUP_DATE],d.cup_mfg_date) as CUPDATE, isnull([CUP_PART_NUM],left([Cup#],charindex('-',Cup#)-1)) as PARTNUM, isnull(p.[LATERAL_VALUE], " &
"d.lateral_value * 10000) as LATVALUE, isnull([LAT_UPPER],0) as LAT_UPPER,isnull([LAT_LOWER],0) as LAT_LOWER, " &
"isnull(p.[BEFORE_WEIGHT],0) as BEFORE_WEIGHT, isnull(p.[AFTER_WEIGHT],0) as AFTER_WEIGHT,isnull([GREASE_UPPER],0) as GREASE_UPPER, " &
"isnull([GREASE_LOWER],0) as GREASE_LOWER,isnull(p.[SPACER_MEASURE], d.Spacer_Measure) as SPACER,isnull([QTY_SPACER_CHANGE],0) as 'CHANGES', " &
"isnull([LATERAL_DATE_TIME],'1999-11-11 11:11:11.111') as LATERAL_DATE_TIME, " &
"isnull([GREASE_DATE_TIME],'1999-11-11 11:11:11.111') as GREASE_DATE_TIME, isnull([LINE_NUM],d.linenum) as LINE, " &
"isnull(BAD_PART, 'BAD_INFO') as Result, isnull([AIR_PRESSURE1], 0) as PRESSURE " &
"FROM [NB_ASSEMBLY].[dbo].[PieceData] p full outer JOIN New_Assembly_Access.dbo.Tbl_Data AS d " &
"ON substring(d.zbarcode,3,6) = right(p.serial_number,6) and month(d.cup_mfg_date) = month(p.cup_date) and " &
"right(d.zbarcode,10) = right(p.cup_part_num,10) join new_assembly_Access.dbo.tbl_job j on j.job# = d.job# where d.job# = #Job2", con)
sql.Parameters.AddWithValue("#Job2", job)
da.SelectCommand = sql
Dim dt As New DataTable
da.Fill(dt)
Invoke(Sub()
dgvJob.DataContext = dt.DefaultView
dgvJob.AutoGenerateColumns = True
dgvJob.CanUserAddRows = False
End Sub)
End Using
End Sub) With {
.IsBackground = True
}
bgThread.Start()
End Sub
Public Sub Button_Click(sender As Object, e As RoutedEventArgs)
txtJob.IsEnabled = False
btnEnter.IsEnabled = False
job = txtJob.Text
ReadDatabase()
End Sub
Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
txtJob.Focus()
End Sub
I am trying to make a query that deletes the user from my database.
But when i confirm to delete the user it gives me an error:
System.Data.SqlClient.SqlException (0x80131904): Must declare the scalar variable "#Username".
Imports System.Data.SqlClient
Public Class DeleteForm
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim RetVal As Integer
Dim conn = New SqlConnection("Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=dbProject;Integrated Security=True")
Using cmd = New SqlCommand("select count(*) from tblLogin where username = #Username and password = #Password", conn)
cmd.Parameters.Add("#Username", SqlDbType.VarChar).Value = txtUsername.Text
cmd.Parameters.Add("#Password", SqlDbType.VarChar).Value = txtPassword.Text
conn.Open()
If conn.State = ConnectionState.Open Then
RetVal = CInt(cmd.ExecuteScalar)
If RetVal = 1 Then
If txtPassword.Text And txtCheckPassword.Text <> "" Then
If txtCheckPassword.Text = txtPassword.Text Then
Dim cancConf As Integer = MessageBox.Show("This cant be undone!" & vbCrLf & "Are you sure?", "Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
If cancConf = DialogResult.Yes Then
Try
Dim queryDelete As String = "DELETE FROM tblLogin WHERE username = #Username"
Dim cmdDelete As New SqlClient.SqlCommand(queryCancellazione, conn)
cmdCancellazione.ExecuteNonQuery()
MsgBox("Account deleted succesfully!")
cmdCancellazione.Dispose()
conn.Close()
LoginForm.Show()
Me.Close()
Catch ex As Exception
MsgBox(ex.ToString())
End Try
ElseIf cancConf = DialogResult.No Then
End If
Else
MsgBox("The passwords arent matching!", MsgBoxStyle.Exclamation)
End If
ElseIf txtPUtenteCANC.Text <> "" And txtPUtenteCONF.Text = "" Then
MsgBox("Please, confirm the password")
End If
Else
MsgBox("User not found!", MsgBoxStyle.Exclamation)
txtNUtenteCANC.Clear()
txtPUtenteCANC.Clear()
txtPUtenteCONF.Clear()
txtNUtenteCANC.Select()
End If
Else
MessageBox.Show("The connection is not open!" & vbCrLf & "The program will close", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End
End If
End Using
End Sub
End Class
You have added that parameter to the SELECT COUNT command but not to the DELETE command.
Dim queryCancellazione As String = "DELETE FROM tblLogin WHERE username = #Username"
Dim cmdCancellazione As New SqlClient.SqlCommand(queryCancellazione, conn)
cmdCancellazione.Parameters.Add("#Username", SqlDbType.VarChar).Value = txtUsername.Text
im having a problem in my codes there's no error showing up and when i press the button nothing happens this is the code im using first one is the update button
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Try
con.Open()
With cmd
.Connection = con
.CommandText = ("Update TBL_EMPLOYEE MiddleName='" & txtMiddleName.Text & "',LastName='" & txtLastName.Text & "', Gender='" & txtGender.Text & "',Age='" & txtupAge.Text & "' ,Address='" & txtupAddress.Text & "', Position='" & txtPos.Text & "',BirthDate='" & Bdate.Text & "' where [FirstName]=#FirstName ")
.Parameters.AddWithValue("FirstName", (txtFirstName.Text))
.ExecuteNonQuery()
.Dispose()
txtFirstName.Text = ""
txtMiddleName.Text = ""
txtLastName.Text = ""
txtGender.Text = ""
txtContactNumber.Text = ""
txtupAge.Text = ""
txtupAddress.Text = ""
txtPos.Text = ""
Bdate.Text = ""
PictureBox2.Image = Nothing
MsgBox("Product Updated", vbInformation, "Information Message")
datagridshow()
End With
Catch ex As Exception
End Try
End Sub
there's no error showing up in the code and nothing happening when i pressed the button and same with my delete button
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Try
con.Open()
With cmd
.Connection = cn
.CommandText = "DELETE * from [TBL_EMPLOYEE] where FirstName='" & DataGridView2.CurrentRow.Cells(1).Value.ToString & "' "
.ExecuteNonQuery()
.Dispose()
.Parameters.Clear()
txtFirstName.Text = ""
txtMiddleName.Text = ""
txtLastName.Text = ""
txtGender.Text = ""
txtContactNumber.Text = ""
txtupAge.Text = ""
txtupAddress.Text = ""
txtPos.Text = ""
Bdate.Text = ""
PictureBox2.Image = Nothing
MsgBox("Employee Deleted", MsgBoxStyle.Information)
datagridshow()
End With
Catch ex As Exception
End Try
End Sub
there's no error and nothing happen also here
this is the form load i am using.
Dim str As String
str = ("Server=LOCALHOST\SQLEXPRESS;Database=Payroll;Trusted_Connection=True;")
cn = New SqlConnection(Str)
cn.Open()
Your UPDATE is missing the SET keyword, and your DELETE has a * that shouldn't be there.
I have actually done some research on this, and result is shown in my work. But I am still having problems populating the combobox. The form runs fine with no errors, but nothing shows up in the combobox. Can anyone help with this issue? I keep running it over, but I have absolutely no idea where the problem is.
Public Class Form1
Private Sub cboModel_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboModel.SelectedIndexChanged
Try
Dim strSelect As String = ""
Dim cmdSelect As OleDb.OleDbCommand
Dim drSourceTable As OleDb.OleDbDataReader
Dim dt As DataTable = New DataTable
If OpenDatabaseConnectionSQLServer() = False Then
MessageBox.Show(Me, "Database connection error." & vbNewLine &
"The application will now close.",
Me.Text + "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End If
cboModel.BeginUpdate()
cboModel.Items.Clear()
strSelect = "SELECT intAutoID, strMake FROM TAutos"
cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
drSourceTable = cmdSelect.ExecuteReader
dt.Load(drSourceTable)
cboModel.ValueMember = "intAutoID"
cboModel.DisplayMember = "strMake"
cboModel.DataSource = dt
If cboModel.Items.Count > 0 Then cboModel.SelectedIndex = 0
cboModel.EndUpdate()
drSourceTable.Close()
CloseDatabaseConnection()
Catch excError As Exception
MessageBox.Show(excError.Message)
End Try
End Sub
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Dim strSelect As String = ""
Dim strModel As String = ""
Dim cmdSelect As OleDb.OleDbCommand
Dim drSourceTable As OleDb.OleDbDataReader
Dim dt As DataTable = New DataTable
If OpenDatabaseConnectionSQLServer() = False Then
MessageBox.Show(Me, "Database Connection Error." & vbNewLine &
"The Application Will Now Close.",
Me.Text + "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End If
strSelect = "SELECT strMake, strModel, strYear, strMileage FROM TAutos WHERE intAutoID = " & cboModel.SelectedValue
cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
drSourceTable = cmdSelect.ExecuteReader
dt.Load(drSourceTable)
txtMake.Text = dt.Rows(0).Item(0)
txtMileage.Text = dt.Rows(1).Item(1)
txtYear.Text = dt.Rows(2).Item(2)
CloseDatabaseConnection()
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Close()
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim strSelect As String = ""
Dim strMake As String = ""
Dim strMileage As String = ""
Dim strYear As String = ""
Dim intRowsAffected As Integer
Dim cmdUpdate As OleDb.OleDbCommand
If OpenDatabaseConnectionSQLServer() = False Then
MessageBox.Show(Me, "Database Connection Error." & vbNewLine &
"The Application Will Now Close.",
Me.Text + "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End If
strMake = txtMake.Text
strMileage = txtMileage.Text
strYear = txtYear.Text
strSelect = "Update TAutos Set strMake = '" & strMake & "', " & "strMileage = '" & strMileage & "', " & "strYear = '" & strYear & "', " & "Where intAutoID = " & cboModel.SelectedValue
MessageBox.Show(strSelect)
cmdUpdate = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
intRowsAffected = cmdUpdate.ExecuteNonQuery()
If intRowsAffected = 1 Then
MessageBox.Show("Update Failed")
End If
CloseDatabaseConnection()
End Sub
End Class