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
Related
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:
I would be grateful if you could help me with a strange behavior on a vb.net project.
I have a Login form.
The user gives username and password and if the credentials are ok, the app goes to another form
Try
con.Open()
Dim sql As New SQLite.SQLiteCommand("Select * From users where username = '" & UsernameTextBox.Text & "' and userpass = '" & PasswordTextBox.Text & "'", con)
Dim dr As SQLite.SQLiteDataReader = sql.ExecuteReader
Dim dt As New DataTable
dt.Load(dr)
If dt.Rows.Count = 1 Then
'there is only one user
Dim f As New MainFrm
f.lbluser.Tag = dt.Rows(0)(3)
f.lbluser.Text = dt.Rows(0)(1)
f.ShowDialog()
Me.Close()
ElseIf dt.Rows.Count = 0 Then
'credentials are wrong
MessageBox.Show("No user with those credentials. Try again!", "Wrong credentials", MessageBoxButtons.OK, MessageBoxIcon.Error)
UsernameTextBox.Text = ""
PasswordTextBox.Text = ""
UsernameTextBox.Focus()
Exit Sub
Else
'credentials are multiple in the database
MessageBox.Show("Issues with the credentials. Code error: LFUE-1010", "Multiple users | LFUE-1010", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
con.Close()
Catch ex As Exception
con.Close()
'there are problems with the connection / or sql
MessageBox.Show("Connection issues - code error: LFDC-1020 " & ex.Message, "DB connection error | LFDC-1020", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
This works perfectly.
In the other form, let's say that I have a button:
If cbkeywords.SelectedIndex = -1 Then
MsgBox("select something")
Exit Sub
End If
Dim d = DirectCast(cbkeywords.SelectedItem, DataRowView).Item("Keyword")
If lstkeywords.Items.Count > 0 Then
For i As Integer = 0 To lstkeywords.Items.Count - 1
If lstkeywords.Items(i).contains(d) Then
MessageBox.Show("there is already value " & d, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
Else
dtkeys.Rows.Add(cbkeywords.SelectedValue, d)
lstkeywords.Items.Add(d)
End If
Next
Else
dtkeys.Rows.Add(cbkeywords.SelectedValue, d)
lstkeywords.Items.Add(d)
End If
if the code has an error then the app goes to Login Form Catch ex As Exception and get the message.
Wherever I have issues with code in different forms, the app goes to Login Form Catch ex As Exception.
I cleaned solution, project, restart but nothing changed.
Any ideas?
Thanks in advance
Do the database code first and then do the other code. Keep them separate. Otherwise, when you do f.ShowDialog(), it is still inside the Try...Catch.
Something like this:
Dim dt As New DataTable
Dim con As New SqliteConnection(yourConnectionString)
Try
Dim sql As New SQLite.SQLiteCommand("Select * From users where username = '" & UsernameTextBox.Text & "' and userpass = '" & PasswordTextBox.Text & "'", con)
Dim dr As SQLite.SQLiteDataReader = sql.ExecuteReader()
dt.Load(dr)
Catch ex As Exception
con.Close()
'there are problems with the connection / or sql
MessageBox.Show("Connection issues - code error: LFDC-1020 " & ex.Message, "DB connection error | LFDC-1020", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
If Sql IsNot Nothing Then
Sql.Dispose()
End If
If con IsNot Nothing Then
con.Dispose()
End If
End Try
If dt.Rows.Count = 1 Then
'there is only one user
Dim f As New MainFrm
f.lbluser.Tag = dt.Rows(0)(3)
f.lbluser.Text = dt.Rows(0)(1)
f.ShowDialog()
Me.Close()
ElseIf dt.Rows.Count = 0 Then
'credentials are wrong
MessageBox.Show("No user with those credentials. Try again!", "Wrong credentials", MessageBoxButtons.OK, MessageBoxIcon.Error)
UsernameTextBox.Text = ""
PasswordTextBox.Text = ""
UsernameTextBox.Focus()
Exit Sub
Else
'credentials are multiple in the database
MessageBox.Show("Issues with the credentials. Code error: LFUE-1010", "Multiple users | LFUE-1010", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
You do not need to open the connection because the .Load method does that and then leaves the connection in the state it was.
Have a look at the code below. This code works on all the textboxes except on the combobox. I guess it is because of the data type. Is there a way to fix it. Please do help me. Thank You!
Dim int As Integer
Dim str As String
Try
int = CInt(txtsid.Text) & CInt(txtsph.Text)
str = CStr(txtsfn.Text) & CStr(txtsln.Text) & CStr(txtint.Text) & CStr(txtsem.Text) & CStr(cbogen.Text)
Catch ex As Exception
MessageBox.Show("Please Type Informations Properly")
Return
End Try
Dim result As Integer = MessageBox.Show("Are you sure you want to proceed?", "Proceed", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If result = DialogResult.Yes Then
UserHomepage.Show()
Me.Hide()
cmdInsert.CommandText = "Insert into student Values(" + txtsid.Text + ",'" + txtint.Text + "','" + txtsfn.Text + "','" + txtsln.Text + "', '" + cbogen.Text + "', " + txtsph.Text + ", '" + txtsem.Text + "');"
cmdInsert.CommandType = CommandType.Text
cmdInsert.Connection = cnnOLEDB
cmdInsert.ExecuteNonQuery()
ElseIf result = DialogResult.No Then
Me.Show()
UserHomepage.Hide()
End If
Comment and explanations in line.
Private Sub UpdateDatabase()
'This entire are of code down to the End Try does nothing
'Any .Text property is already a String and does not need CStr
'In the int = line you have 2 Strings that you convert to Integers, Then they must
'be changed back to Strings in order to concatenate them, Then the new string is again changed to an
'integer!! Argh!
'Dim int As Integer
'Dim str As String
'Try
' int = CInt(txtsid.Text) & CInt(txtsph.Text)
' str = CStr(txtsfn.Text) & CStr(txtsln.Text) & CStr(txtint.Text) & CStr(txtsem.Text) & CStr(cbogen.Text)
'Catch ex As Exception
' MessageBox.Show("Please Type Informations Properly")
' Return
'End Try
'Changed Integer to DialogResult
Dim result As DialogResult = MessageBox.Show("Are you sure you want to proceed?", "Proceed", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If result = DialogResult.Yes Then
UserHomepage.Show()
Me.Hide()
Try 'This is the place for Try...End Try. Networks and database connections can have
'all sorts of unexpected errors.
'The Using blocks ensure that your objects are closed and disposed even if there is an error.
'Keep your connections local
Using cnnOLEDB As New OleDbConnection("Your connection string")
'Pass your command text and the connection to the constructor of the command
Using cmdInsert As New OleDbCommand("Insert into student Values(?,?,?,?,?, ?,?);", cnnOLEDB)
cmdInsert.CommandType = CommandType.Text
'USE PARAMETERS to avoid SQL injection
'If this first parameter is an autonumber field, it should be removed
'from the Insert statement. Also remove a "?" You may have to list the
'fields in the first part of the Insert to match the question marks.
cmdInsert.Parameters.Add("#sid", OleDbType.Integer).Value = txtsid.Text
cmdInsert.Parameters.Add("#int", OleDbType.VarChar).Value = txtint.Text
cmdInsert.Parameters.Add("#sfn", OleDbType.VarChar).Value = txtsfn.Text
cmdInsert.Parameters.Add("#sln", OleDbType.VarChar).Value = txtsln.Text
cmdInsert.Parameters.Add("#gen", OleDbType.VarChar).Value = cbogen.Text
cmdInsert.Parameters.Add("#sph", OleDbType.Integer).Value = txtsph.Text
cmdInsert.Parameters.Add("#sem", OleDbType.VarChar).Value = txtsem.Text
cnnOLEDB.Open()
cmdInsert.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
'The following ElseIf is useless
'Me is already visible and UserHomepage is not
'ElseIf result = DialogResult.No Then
' Me.Show()
' UserHomepage.Hide()
End If
End Sub
'Do your validation here
Private Sub TextBox1_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
'For a string field
If TextBox1.Text = "" Then
MessageBox.Show("Required field")
e.Cancel = True
TextBox1.Select(0, TextBox1.Text.Length)
End If
'Or
'For a number field
Dim myInt As Integer
If Not Int32.TryParse(TextBox1.Text, myInt) Then
MessageBox.Show("Requires number")
e.Cancel = True
TextBox1.Select(0, TextBox1.Text.Length)
End If
End Sub
I have two comboboxes, a messagebox and a Send button. When the app startups and I click on the Send button with the comboboxes and messagebox empty, a pop-up box comes up and says "Select a client" After doing this, I go back to the database and see that it has added a new record to that table, even though I didn't put in any data after clicking on the "Send" button. Same applies for when one of the three controls I have has data in it, but the other two don't, and the program asks me to enter that data before it succeeds. But it still adds the record despite having those If Statements. What am I doing wrong?
My code:
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
con.Open()
Using cmd As New SqlCommand
cmd.Connection = con
cmd.CommandText = "insert into tblMyTable(Client, UserName, Message) values('" & cboClient.Text & "', '" & cboUser.Text & "', '" & rtfMessage.Text & "')"
cmd.ExecuteNonQuery()
End Using
If cboClient.Text = "" Then
MsgBox("Select a client")
ElseIf cboUser.Text = "" Then
MsgBox("Select a user")
ElseIf rtfMessage.Text = "" Then
MsgBox("Enter a message")
Else
MsgBox("Message Sent")
End If
con.Close()
End Using
I think you want something like this (note this does not address parameterization concerns):
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
If cboClient.Text = "" Then
MsgBox("Select a client")
ElseIf cboUser.Text = "" Then
MsgBox("Select a user")
ElseIf rtfMessage.Text = "" Then
MsgBox("Enter a message")
Else
con.Open()
Using cmd As New SqlCommand
cmd.Connection = con
cmd.CommandText = "insert into tblMyTable(Client, UserName, Message) values('" & cboClient.Text & "', '" & cboUser.Text & "', '" & rtfMessage.Text & "')"
cmd.ExecuteNonQuery()
End Using
MsgBox("Message Sent")
End If
con.Close()
End Using
Similar solution to #OldProgrammer, with an attempt at parameterized insert.
Private Sub SendButton_Click(sender As System.Object, e As System.EventArgs) Handles SendButton.Click
Try
If writeMessage() Then
MessageBox.Show("Message sent.", "Success")
End If
Catch ex As Exception
MessageBox.Show(String.Concat("An error occurred sending this message:", ex.Message))
End Try
End Sub
Private Function writeMessage() As Boolean
If isValidMessage() Then
writeMessageInfo()
Return True
End If
Return False
End Function
Private Sub writeMessageInfo()
Using con As New SqlConnection(yourConnectionString)
con.Open()
Using cmd As New SqlCommand
cmd.Connection = con
cmd.Parameters.Add(New SqlParameter("clientValue", cboClient.Text))
cmd.Parameters.Add(New SqlParameter("userValue", cboUser.Text))
cmd.Parameters.Add(New SqlParameter("messageText", rtfMessage.Text))
cmd.CommandText = "insert into tblMyTable(Client, UserName, Message) values(#clientValuem, #userValue, #messageText)"
cmd.ExecuteNonQuery()
End Using
con.Close()
End Using
End Sub
Private Function isValidMessage() As Boolean
If cboClient.SelectedIndex = -1 Then
MessageBox.Show("Please select a client.", "Missing info")
cboClient.Focus()
Return False
End If
If cboUser.SelectedIndex = -1 Then
MessageBox.Show("Please select a user.", "Missing info")
cboUser.Focus()
Return False
End If
If rtfMessage.Text = String.Empty Then
MessageBox.Show("Please enter a message.", "Missing info")
rtfMessage.Focus()
Return False
End If
Return True
End Function
Dim con As New SqlConnection
con.ConnectionString = "Data Source=(local);Integrated Security=True"
Dim cmd As New SqlCommand("SELECT * FROM login where Admin = #Admin AND Password = #Password ", con)
'Set up parameters for the sqlcommand
cmd.Parameters.AddWithValue("#Admin", comb.Text)
cmd.Parameters.AddWithValue("#Password", Txtpass.Text)
'If the username or password is empty then throw an error
If comb.Text = String.Empty Then
MessageBox.Show("Please choose the username.", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
ElseIf Txtpass.Text = String.Empty Then
MessageBox.Show("Please enter the password.", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Try
'Open the connection and declare an sqlreader
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader
'If our reader has one or more rows then read those rows and compare the text
If reader.HasRows = True Then
reader.Read()
Dim ReadUserName As String
Dim ReadUserID As String
ReadUserID = reader(3) 'This is the first field returned, most likely UserID
ReadUserName = reader(1) 'This is the second field returned
'If the username and password match then it's a success
If comb.Text = reader("Admin").ToString And Txtpass.Text = reader.Item("Password").ToString Then
MessageBox.Show("Login successful" & ReadUserName)
Else
'If they don't match than throw an error
MessageBox.Show("Login Failed." & Environment.NewLine & _
"UserName and Password are casesensitive.", _
Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End If
Catch ex As Exception
MessageBox.Show(ex.ToString, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
con.Close()
End Try
End If
You're telling your code to read one row:
If reader.HasRows = True Then
reader.Read()
If you want to read all rows from your SqlDataReader, you need to use a loop (here in C#):
while (reader.Read())
{
..... (read the individual values for the current row) ......
}
The .Read() call will return true, as long as a row has been read from the SqlDataReader - now fetch the data from the row, store it or process it - whatever you need to do - and then your next call to reader.Read() checks if another row can be read. If so: repeat your processing.
If reader.Read() return false, then all rows have been read and you're done.
If command runs the code only once and read one row. So use while loop to read all the line
If reader.HasRows = True Then
While reader.Read()
Dim ReadUserName As String
Dim ReadUserID As String
ReadUserID = reader(3) 'This is the first field returned, most likely UserID
ReadUserName = reader(1) 'This is the second field returned
'If the username and password match then it's a success
If comb.Text = reader("Admin").ToString And Txtpass.Text = reader.Item("Password").ToString Then
MessageBox.Show("Login successful" & ReadUserName)
Else
'If they don't match than throw an error
MessageBox.Show("Login Failed." & Environment.NewLine & _
"UserName and Password are casesensitive.", _
Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End While ' I don't know much of vb.net'
End If