auto number in data grid view and access database - vb.net

I wanted to make a program using access database and make it auto number the rows but when I delete a row the order of the rows is incorrect and the program starts with the last row number
The deletion code I used:
Sub delete()
Try
If MsgBox("Are You Sure Delete This Record", vbQuestion + vbYesNo) = vbYes Then
conn.Open()
Dim cmd As New OleDb.OleDbCommand("Delete from MedicineDB Where ID=#ID", conn)
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("#ID", txtID.Text)
i = cmd.ExecuteNonQuery
If i > 0 Then
MsgBox("Record Delete Success !", vbInformation)
Else
MsgBox("Failed", vbCritical)
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
loadingDatagridView()
clear()
End Sub
that is the result:

Related

how can i push a msgbox if record is not found in Database using vb.net

seeking help how i can push a msgbox error if a record is not in the database or no data in the database. im using vb.net and sql to check the record. not sure how to do,
here is my code
Try
myConnection.Open()
str = "SELECT * FROM tblEmp WHERE (EmpID = '" & ADS.UserEmpID & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
'Main.BGCPnl.Visible = True
BGC1 = dr("PreStartChecks").ToString
BGC2 = dr("EmpName").ToString
//>Here is my code for the error message when record is not
found, im not sure what will be the right code.
i used count parameter
BGCEmp = dr(ADS.UserEmpID)
If BGCEmp.Count = 0 Then
MsgBox("no record")
Exit Sub
End If
End While
Catch ex As Exception
MsgBox("Unable to Connect to BGC DB. You may not have access or DB not available." & ex.ToString)
End Try
myConnection.Close()
You should learn how to properly use the Read method and the HasRows property of your data reader. If there can never be more than one record but there might be none then use just Read:
If myDataReader.Read() Then
'There is a row and you can access its data here.
Else
'There are no rows.
End If
If there may be multiple rows and either there can't be no rows or you don't need to do anything specific in the case that there are no rows then just use Read:
While myDataReader.Read()
'Access the current row here.
End While
If there are no rows then you never enter the loop and execution simply continues after that.
If there may be zero, one or more rows and you do need to do something specific in the case where there are none, use both HasRows and Read:
If myDataReader.HasRows Then
'There is at least one row so read the data.
While myDataReader.Read()
'Access the current row here.
End While
Else
'There are no rows.
End If
There may be situations where you only care whether there is data but you don't need the data itself. In that case, just use HasRows:
If myDataReader.HasRows Then
'There is a at least one row
Else
'There are no rows.
End If
In cases like that though, I'd suggest that you should be doing something like using a COUNT function in your query and calling ExecuteScalar rather than calling ExecuteReader.
Try
myConnection.Open()
str = "SELECT * FROM tblEmp WHERE (EmpID = '" & ADS.UserEmpID & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read()
BGC1 = dr("PreStartChecks").ToString
BGC2 = dr("EmpName").ToString
End While
Else
MessageBox.Show("No Record found", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
Catch ex As Exception
MsgBox("Unable to Connect to BGC DB. You may not have access or DB not available." & ex.ToString)
End Try
myConnection.Close()
Read documentation about Read() and HasRows.

$exception is not declared, it may be inaccessible due to its protection level

Public Sub cmdPush_Click(sender As Object, e As EventArgs) Handles cmdPush.Click
If MessageBox.Show("Are you sure you want to add this record?", "Adding records", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) = DialogResult.Yes Then
Try
Call ConntoDB()
conn.Open()
Dim cmd2 As SqlCommand
cmd2 = New SqlCommand
cmd2.Connection = conn
cmd2.CommandText = "INSERT INTO studentaccounts (
Account_Number,
Tuition_Fee,
iTuition_Fee,
Tuition_Fee_DC,
Bus_Fee,
iBus_Fee,
Bus_Fee_DC,
Full_Name) VALUES (
#accountnumber,
#tuitionfee,
#ituitionfee,
#tuitionfeedc,
#busfee,
#ibusfee,
#busfeedc,
#fullname)"
cmd2.Parameters.AddWithValue("#accountnumber", Me.txtaccount.Text)
cmd2.Parameters.AddWithValue("#tuitionfee", Me.lbltuitionfee.Text)
cmd2.Parameters.AddWithValue("#ituitionfee", frmSetupTuitionFee.txttuition.Text)
cmd2.Parameters.AddWithValue("#tuitionfeedc", frmSetupTuitionFee.txtdiscountrate.Text)
cmd2.Parameters.AddWithValue("#fullname", Me.lblfullname.Text)
cmd2.Parameters.AddWithValue("#busfee", Me.lblbusfee.Text)
cmd2.Parameters.AddWithValue("#ibusfee", frmSetupBusFee.txtbus.Text)
cmd2.Parameters.AddWithValue("#busfeedc", frmSetupBusFee.txtdiscountratebus.Text)
cmd2.ExecuteNonQuery()
MsgBox("Data has been added!")
Loadlastrow()
conn.Dispose()
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
conn.Dispose()
conn.Close()
End Try
Else
End If
End Sub
I am so clueless im getting an error of $exception is not declared, it may be inaccessible due to its protection level. What have I missed?
Also this code was still working, i saved the file went for lunch and when I came back this issue is occurred.

Delete button code sometimes working

How to debug the following code?
Dim deleteok As String = MsgBox("Do you really want to delete this record", MsgBoxStyle.YesNo, "updating records")
If vbYes Then
Try
con.Open()
cmd.Connection = con
cmd.CommandText = "Delete From TB_stinfo where id=?"
cmd.Parameters.Add(New OleDbParameter("?", TextBox1.Text))
cmd.ExecuteNonQuery()
MessageBox.Show("one record is deleted")
Catch ex As Exception
MessageBox.Show("Error while deleting record on table..." & ex.Message, "Delete Records")
Finally
dt.Clear()
Form1_Load(sender, e)
clear()
checkcon()
End Try
Else
MsgBox("This record is not deleted")
End If
I reformatted your code so it was more readable:
Dim deleteok As String = MsgBox("Do you really want to delete this record", MsgBoxStyle.YesNo, "updating records")
If vbYes Then
Try
con.Open()
cmd.Connection = con cmd.CommandText = "Delete From TB_stinfo where id=?"
cmd.Parameters.Add(New OleDbParameter("?", TextBox1.Text))
cmd.ExecuteNonQuery()
MessageBox.Show("one record is deleted")
Catch ex As Exception
MessageBox.Show("Error while deleting record on table..." & ex.Message, "Delete Records")
Finally
dt.Clear()
Form1_Load(sender, e)
clear()
checkcon()
End Try
Else
MsgBox("This record is not deleted")
End If
The number one issue I see here is that we do not see what the value of the key is you're deleting on , nor the format of the data that's in the table to delete from. It's impossible to determine what exactly is wrong from this code.
My suggestion is to set a breakpoint on this line cmd.ExecuteNonQuery() and see what the value of TextBox1.Text is and make sure it is what you expect it to be, look for leading/trailing spaces or anything else that's unexpected.. Other than that there isn't much else to go on here in terms of context.

Update a record if it already exists in access with vb

I'm trying to check if a client is already signed in. if he is, then the button will sign him out instead of adding a new record altogether and I'm struggling to find a solution.
this is the current code I'm using:
Private Sub btnSignIn_Click(sender As Object, e As EventArgs) Handles btnSignIn.Click
Dim cmd As New OleDbCommand
' cnn = cnn
Try
If Not cnn.State = ConnectionState.Open Then 'open the database connection
cnn.Open()
End If
If txtClientName.Text = Nothing Then 'check to see if the name field is empty
MsgBox("Please enter a name to sign in")
txtClientName.Focus()
ElseIf txtDateTime.Text = Nothing Then ' checks if timeslip is empty
MsgBox("Please enter a valid time to sign in")
txtDateTime.Focus()
Else 'if no fields are empty proceed with code
cmd.Connection = cnn
cmd.CommandText = "INSERT INTO LogSheet (ClientName, SignInTime, CurrentDate)" &
"VALUES(?, ?, ?)"
cmd.Parameters.AddWithValue("#p1", txtClientName.Text.ToString.ToUpper)
cmd.Parameters.AddWithValue("#p2", txtDateTime.Text)
cmd.Parameters.AddWithValue("#p3", Date.Now().ToShortDateString)
cmd.ExecuteNonQuery()
RefreshData()
txtClientName.Clear()
txtDateTime.Clear()
End If
Catch ex As Exception
MessageBox.Show(ex.Message & " - " & ex.Source)
cnn.Close()
End Try
End Sub
there is no validation there, but ive tried many different codes with no luck..
I simply want the script to check, if client is signed in, then give an error "Client already signed in" else if he signs out, just update the signout field
thanks
This is an image of what my program is1
Update the structure of your Database Table (LogSheet) to include the following fields. ClientName,SignInTime,SignInRelation,SignOutTime,SignOutRelation,CurrentDate
If the client is signed in then the SignInTime for today (CurrentDate) will have a value, you can then populate the value for SignOutTime.
This is one possible way you could code it:
This code is untested, but you should get the idea.
Sub BtnSignIn_Click()
If IsUserLoggedIn(txtClientName.Text) = True Then
'Client has been logged in already. Do Action.
Else
'Client has not been logged in today. Do Action.
End If
End Sub
Function IsUserLoggedIn(UserName As String) As Boolean
Dim sql = "Select SignOutTime From LogSheet Where CurrentDate=#D AND ClientName=#C"
Try
Using cnn As New OleDbConnection
Using cmd As New OleDbCommand(sql, cnn)
cnn.Open()
cmd.Parameters.AddWithValue("#D", Today.Date.ToShortDateString)
cmd.Parameters.AddWithValue("#C", UserName)
Dim result = cmd.ExecuteScalar
If result Is Nothing OrElse result Is DBNull.Value OrElse String.IsNullOrEmpty(result.ToString) Then
Return False
Else
Return True
End If
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message, "Error: " & System.Reflection.MethodBase.GetCurrentMethod.Name, MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Function
You should insert DateTime values:
cmd.Parameters.AddWithValue("#p2", DateTime.Parse(txtDateTime.Text))
cmd.Parameters.AddWithValue("#p3", DateTime.Today)

empty record after delete from dataset

after deleting record from the form there is an empty record until clos the form and reopen it '
below is my code
Try
Dim delrecord As String = "delete from unitinfo where unitCode = '" & txtUcode.Text & "' "
Dim delcon As New SqlConnection(sqlcon)
delcon.Open()
Dim cmdsqldel As New SqlCommand(delrecord, delcon)
cmdsqldel.ExecuteNonQuery()
If MessageBox.Show("Do you really want to Delete this Record?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then
Exit Sub
Else
End If
delcon.Close()
Catch ex As Exception
End Try
Try
If MessageBox.Show("Do you really want to Delete this Record?",
"Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then
Exit Sub
Else
Dim delrecord As String = "delete from unitinfo
where unitCode = '" & txtUcode.Text & "' "
Dim delcon As New SqlConnection(sqlcon)
delcon.Open()
Dim cmdsqldel As New SqlCommand(delrecord, delcon)
cmdsqldel.ExecuteNonQuery()
delcon.Close()
MessageBox.Show("Record Successfuly Deleted")
/* Here you should refresh your datagridview if you have or any thing else*/
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
' This line executes whether or not the exception occurs.'
If delcon.State = ConnectionState.Open Then delcon.Close()
End Try