DELETE VALIDATION for DataGridView - database

I wan't some help about my DELETE button.
At first my the code was a success. It can delete both the data's from the vb program as well as the data of the database which is located at MS Access.
But, when I added some validations to my DELETE button, adding it some MessageBoxstyle and MessageBoxButton it just won't work. It only deletes the entry of the textboxes not the data itself.
My Question Would be...
I wan't my program to not only DELETE the data on the textboxes but also the data that corresponds on the DatagridView when I press "YES" on the confirmation message. And when I click on the NO button it'll only just remain as it is. HOW do you do this???
Please someone help me. I'm new to this and still learning. I'm still a student and I really need this for my System... thank you!
Here is my code!
Imports System.Data.OleDb
Imports System.Text.RegularExpressions
Public Class Monitoring_Form
Dim connect As OleDbConnection
Dim adapter As OleDbDataAdapter
Dim commnd As OleDbCommand
Dim dataset As DataSet
Dim datatable As DataTable
Dim table As DataTableCollection
Dim binding As New BindingSource
Dim id As Integer
Dim Email As Boolean
Private Sub btn_cdelete_Click(sender As System.Object, e As System.EventArgs) Handles btn_cdelete.Click
txt_customerID.Text = id
If MessageBox.Show("Are you sure you wan't to DELETE this record?", "Delete Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = Windows.Forms.DialogResult.Yes Then
commnd = New OleDbCommand("delete FROM CustomersInfo WHERE FirstName = '" + txt_firstname.Text + "'", connect)
commnd.ExecuteNonQuery()
MsgBox("ENTRY SUCCESSFULLY DELETED!")
txt_customerID.Text = ""
txt_firstname.Text = ""
txt_lastname.Text = ""
txt_add.Text = ""
txt_cnumber.Text = ""
txt_email.Text = ""
'' Me.dgv_1.Rows.RemoveAt(Me.dgv_1.CurrentRow.ToString())
Else
End If
End Sub
I've just edited my Question to make it clear for you guys. Please help and sorry for the mistake.
This is the revision of my code

Related

Autocomplete TextBox Column in DataGridView Stopped working

I have a datagridview with one of its column as TextBox. I wrote a function to populate values from database and suggest values to autocomplete the text. I achieved it, and then I started coding to make a column auto increment (Sr.No) , so I wrote some more lines of code and changed some properties and all of a sudden the textbox stopped auto-completing. Now I tried every possible step to make it work but failed. I dont know what is the property that I changed affected this.
I am putting my code here, please help
This is the code for Editingcontrolshowing event...
Private Sub DataGridView2_EditingControlShowing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView2.EditingControlShowing
DataGridView2.BeginEdit(True)
Dim autoText As TextBox = TryCast(e.Control, TextBox)
If autoText IsNot Nothing Then
autoText.AutoCompleteMode = AutoCompleteMode.SuggestAppend
autoText.AutoCompleteCustomSource = AutoCompleteLoad()
autoText.AutoCompleteSource = AutoCompleteSource.CustomSource
End If
End Sub
This is the autocomplete function where I loaded values...
Public Function AutoCompleteLoad() As AutoCompleteStringCollection
Dim str As AutoCompleteStringCollection = New AutoCompleteStringCollection()
Dim ConnectionString As SqlConnection = New SqlConnection("data source=ADMIN-PC\SQLEXPRESS; database=billdev;Trusted_Connection=yes;")
Dim strSQL As String = "SELECT * from bill;"
Dim SQLcommand As New SqlCommand(strSQL, ConnectionString)
ConnectionString.Open()
Dim reader As SqlDataReader
reader = SQLcommand.ExecuteReader()
While reader.Read()
str.Add(reader.Item(1))
End While
Return str
End Function
This is the extra code I added before it stopped working, but I think this doesn't make any difference
Private Sub DataGridView2_RowPrePaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPrePaintEventArgs) Handles DataGridView2.RowPrePaint
If e.RowIndex >= 0 Then
Me.DataGridView2.Rows(e.RowIndex).Cells(0).Value = e.RowIndex + 1
End If
End Sub
I found the solution.
I tried changing every property of the datagridview randomly. And finally got to the point.
It is the WRAP property of the column itself.

VB.NET - .accdb database not saving changes

I can't figure out why my code won't save to my .accdb database.
I am fetching data from a .accdb database file and displaying it in a DataGridView, and then allowing changes to be made to it there. (This is a stock control system.) After making changes, the user is meant to be able to send the data back so it is saved in the .accdb file.
I have looked online everywhere and tried multiple different ways of doing this. This is the way I am currently using to solve the problem, but when running the code it does not save to the .accdb file. (However, it throws up no errors.)
Public Class Database
Dim datatable As DataTable
Dim adapter As OleDb.OleDbDataAdapter
Dim dbCon As New OleDb.OleDbConnection
Dim dbProvider As String = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
Dim dbRsrc As String = "Data Source =" & System.IO.Directory.GetCurrentDirectory & "/Resources/List.accdb"
Dim binding As BindingSource
Dim cmdBuilder As OleDb.OleDbCommandBuilder
Private Sub Database_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dbCon.ConnectionString = dbProvider & dbRsrc
dbCon.Open()
adapter = New OleDb.OleDbDataAdapter("Select * FROM List", dbCon)
datatable = New DataTable
adapter.FillSchema(datatable, SchemaType.Source)
adapter.Fill(datatable)
binding = New BindingSource
binding.DataSource = datatable
dbCon.Close()
StockTable.DataSource = binding
End Sub
Private Sub SaveBtn_Click(sender As Object, e As EventArgs) Handles SaveBtn.Click
'insert validation here
Try
dbCon.ConnectionString = dbProvider & dbRsrc
dbCon.Open()
cmdBuilder = New OleDb.OleDbCommandBuilder(adapter)
adapter.AcceptChangesDuringUpdate = True
adapter.Update(datatable)
dbCon.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString() & " Save Unsuccessful.")
End Try
End Sub
End Class
Not sure where I'm going wrong - when I hit the 'save' button, it should connect to the database, build a SQL query to update it and then update my datatable + .accdb database, right?
To test it, I've tried editing multiple columns and saving it, but when opening the file it still says the same values as it had before.
Any suggestions/pointers? I'm pretty newbie to VB.NET, learnt it about 3 months ago and only just starting to get fully into it.
Many thanks to the user "jmcilhinney" who helped me to reach this answer. I feel highly stupid at not realising that my code was working.
I used
Debug.WriteLine("Update value: " & adapter.Update(datatable))
Debug.WriteLine("Connection str: " & dbProvider & dbRsrc)
to find that my update command worked, and that in fact the output of my database file was in the /bin/ folder. I didn't realise that it used the /bin/ folder, and was looking in the root folder with the .VB files, etc.

delete record from database in listview in vb

I have a problem. In the properties of listview which is checkboxes = "True". Using this checkbox, I want to delete the data in listview and in the database.
Below is the code:
If MessageBox.Show("Do you really want to DELETE this record?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then
MsgBox("Operation cancel", MsgBoxStyle.Information, "Information")
End If
dbSource = "Data Source=LAILATUL-PC\SERVER;Initial Catalog=HotelManagementSystem;Integrated Security=True"
Dim sql As String = "DELETE FROM [Room] WHERE Room_Code = #code"
Using con = New SqlConnection(dbSource)
Using cmd = New SqlCommand(sql, con)
con.Open()
For Each lvItem As ListViewItem In ListViewRoom.Items
If lvItem.Checked Then
cmd.Parameters.AddWithValue("#code", ColumnRoomCode.Text)
cmd.ExecuteNonQuery()
lvItem.Remove()
End If
Next
End Using
End Using
Using above code, only the data in listview is deleted. The data in the database not deleted.
The interface for listviewitem:
Thank you if you all can help me. :)
A Command should be executed to have any effect on the database. You need to add this
cmd.ExecuteNonQuery()
in every loop.
Also the connection could be opened just before entering the loop and should be closed afterward. (Using Statement is recommended here)
Said that, please take a look on Parameterized queries because your code is open to Sql Injections and parsing problems. Also the sql command to delete a record doesn't need a list of fields after the FROM table part.
Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
dbSource = "Data Source=LAILATUL-PC\SERVER;Initial Catalog=HotelManagementSystem;Integrated Security=True"
' Parameterized query
Dim sql As String = "DELETE FROM [Room] WHERE Room_Code = #code"
' Using statement to ensure proper closing and disposing
' of the objects SqlConnection and SqlCommand
using con = New SqlConnection(dbSource)
using cmd = New SqlCommand(sql, con)
con.Open()
' Add a parameter just one time before the loop with an empty string
cmd.Parameters.AddWithValue("#code", "")
For Each lvItem As ListViewItem In ListViewRoom.Items
If lvItem.Checked Then
' Set the parameter value with the value extracted from the ListViewItem
Dim RoomCode = lvItem.Text
cmd.Parameters("#code").Value = RoomCode
cmd.ExecuteNonQuery()
lvItem.Remove()
End If
Next
End Using
End Using
End Sub
One last note. The ColumnRoomCode textbox (?) is always the same, so calling delete one time is enough, but I suppose that this should be changed with some value extrated by you current ListViewItem

VB.NET issue loading textboxes with data from SQL Server

I have some textboxes (using VS2010) I'm trying to populate with values from columns in a SQL Server database based on what item someone selects from a combobox. At first I was able to display the values for the first item in the combobox, but now nothing at all displays when I debug. Code:
Private Sub loadfields(sender As System.Object, e As System.EventArgs) Handles client_selection_combobox.SelectedIndexChanged
Using myconnection As New SqlConnection("connection string")
Dim loadfields As String = "SELECT company FROM ClientFileDatabase WHERE ClientFileDatabase.File_Name=#company;"
Dim loadfields_sqlcommand As New SqlCommand(loadfields, myconnection)
loadfields_sqlcommand.Parameters.Add("#company", SqlDbType.NVarChar)
loadfields_sqlcommand.Parameters("#company").Value = client_selection_combobox.SelectedIndex.ToString
Dim loadfields_dataadapter As New SqlDataAdapter
loadfields_dataadapter.SelectCommand = loadfields_sqlcommand
Dim loadfields_dataset As DataSet = New DataSet()
loadfields_dataadapter.Fill(loadfields_dataset, "ClientFileDatabase")
Dim loadfields_dataview = New DataView(loadfields_dataset.Tables("ClientFileDatabase"))
companyname_textbox.DataBindings.Clear()
companyname_textbox.DataBindings.Add("Text", loadfields_dataview, "Company")
taxid_textbox.DataBindings.Clear()
taxid_textbox.DataBindings.Add("Text", loadfields_dataview, "TaxIDNumber")
accountmanager_textbox.DataBindings.Clear()
accountmanager_textbox.DataBindings.Add("Text", loadfields_dataview, "AccountManager")
etc...
End Using
End Sub
I've also tried using the SelectedValueChanged and SelectionChangeCommitted event handlers to no avail. Also tried using a refresh after setting the databindings, didn't help. Any advice welcome, thanks!
I personally like to use datatables, I find them easier to work with. I'm sure you will have more code to check to make sure dt.rows.count > 0 before actually attempting to work with the data, but here is how I would do it.
Dim loadfields_dataadapter As New SqlDataAdapter
Dim dt As New DataTable
loadfields_dataadapter.Fill(dt)
companyname_textbox.text = dt.Rows(0).Item("Company")
taxid_textbox.text = dt.Rows(0).Item("TaxIDNumber")
accountmanager_textbox.text = dt.Rows(0).Item("AccountManager")
Also, keep in mind that NULL fields in the database can cause runtime errors, so you may have to check for those as well.

Unable to display SQL database data on Visual basic form

I am facing a problem displaying the records of my table on the visual basic form I have created.
This is my code :
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
myconnection = New SqlConnection("server=HOME-PC\SQLEXPRESS;uid=sa;pwd=123;database=college")
myconnection.Open()
mycommand = New SqlCommand("SELECT * from demo3)", myconnection)
Dim mySqlDataAdapter As New SqlDataAdapter(mycommand)
Dim mydsStudent As New DataSet()
mySqlDataAdapter.Fill(mydsStudent, "Student")
ra = mycommand.ExecuteNonQuery()
MessageBox.Show("Data Displayed" & ra)
myconnection.Close()
End Sub
End Class
Note: my database name is "college" , table name is "demo3" . Table contains 2 columns namely name and roll no. How to display the data in those columns on the visual basic form that I have created ?
You don't need to call execute non query. You can bind the dataset to a DataGridView. Like this
Dim DataGridView1 as new DataGridView()
DataGridView1.DataSource = mydsStudent
'Your table goes here, not sure about the exact propety name, hope it works.
DataGridView1.DisplayMember = "demo3"
Me.Controls.Add(DataGridView1)

Resources