How to delete a record in VB.net with Access database? - vb.net

I am a beginner so I followed a tutorial on YouTube and made a program in VB.net using Windows Form that connects to an Access database. The program works, it can move to Previous record, Next record, Add new record and Save. However, the Delete button doesn't work.
I have tried searching for solutions and it was mentioned that I needed to have a Primary Key in the Access database or it wouldn't create a Delete command. So, I set a Primary Key then ran the program but Delete still doesn't work.
I've read that I need to configure the TableAdapter Configuration Wizard but they didn't specify on what exactly I should do. I tried messing around a bit and when I clicked on the Properties of the Table Adapter, I now see a DeleteCommand. However, I'm not sure of what to do with it or how to make it work.
This is what the delete button does
Private Sub DeleteBtn_Click(sender As Object, e As EventArgs) Handles DeleteBtn.Click
PatientRecordsBindingSource.RemoveCurrent()
End Sub
And this is what the save button does:
Private Sub SaveBtn_Click(sender As Object, e As EventArgs) Handles SaveBtn.Click
On Error GoTo SaveErr
PatientRecordsBindingSource.EndEdit()
PatientRecordsTableAdapter.Update(DatabaseDataSet.PatientRecords)
MessageBox.Show("Ok")
SaveErr:
Exit Sub
So, I run the program and I can add and save new records in the table. But when I select a record from the table and then click the Delete button, it only deletes the record on the program. When I check the Access file, the supposedly deleted record is still there. But then I ran the program again and the record I tried to delete is back in the table, like nothing happened.
EDIT: I created a new Access Database file, made sure I assigned a Primary Key then tried it on a new form. It worked, but I am still wondering if I can still fix my problem with the old form.

Related

How to save, edit, and create new record in Access Query with VB.NET

I have a task from school to make a simple program with VB.NET and currently having an issue now. I've connected my MS Access Query (Query, not Table) with my form in VS2015. The program run smoothly, but when I want to update the data, this error message came up
TableAdapterManager contains no connection information. Set each TableAdapterManager TableAdapter property to a valid TableAdapter instance.
I used this following code to update the database
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Me.Validate()
Me.JoblistBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.Joblist)
End Sub
I need this program to run as late as Thursday.
Does anyone know how to fix this problem? Thanks before.

VB.NET Check for keydown on dragdrop

I've tried searching quite a bit for this answer but haven't been able to find a good solution.
I have a datagridview on my form where users can drag and drop files onto the grid and certain columns are filled in. This works fine.
I want to be able to check if a user has a certain key pressed at the time the file is dropped. If so, I want to use that to add specific data to one of the columns in the datagrid.
Is this possible?
EDIT:
I have used keydown outside of dragdrop before but it seems that I'm missing something. The code I have is below. No matter what I do, I never get "T is pressed" but I always get "T is not pressed".
Private Sub frmReader_DragDrop(sender As Object, e As DragEventArgs) Handles Me.DragDrop
Dim files As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
If Keyboard.IsKeyDown(Keys.T) Then
MsgBox("T is pressed.")
' Put certain info into the datagridview
Else
MsgBox("T is not pressed.")
' Put other data into the datagridview
End If
End Sub
God, embarassing... I changed "Keys.T" to "Key.T" and it's working fine. Sorry for the bother.

Adding data in vb.net application does not change ms access database file

I am creating a library software. I have connected an access database with my vb application. In "Add book form", whenever i add a book in there, it shows in datagridview below it but as i restart the application, i find that data is gone as saving data through form is not affecting my database file.
Here is the code:
Public Class addForm
Private Sub BooksBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs)
Me.Validate()
Me.BooksBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.DataDataSet)
End Sub
Private Sub BooksBindingNavigatorSaveItem_Click_1(sender As Object, e As EventArgs) Handles BooksBindingNavigatorSaveItem.Click
Me.Validate()
Me.BooksBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.DataDataSet)
End Sub
Private Sub addForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DataDataSet.Books' table. You can move, or remove it, as needed.
Me.BooksTableAdapter.Fill(Me.DataDataSet.Books)
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Try
BooksBindingSource.EndEdit()
BooksTableAdapter.Update(Me.DataDataSet.Books)
MessageBox.Show("Book added successfully")
Catch ex As Exception
MessageBox.Show("Error")
End Try
End Sub
End Class
Name of my table is "Books". And also it shows "Book added successfully" after clicking on add btn.
Here is a screenshot of the folder structure of one of my projects that uses an access db:
Circled in BLUE is the accessdb that I added to the project. This is the DB file I see in Solution Explorer
Circled in RED is a copy of the blue DB; it is copied to the bin\Debug folder every time I run a build (start the app)
The program runs from the bin\Debug folder (or release if you're using that build configuration) and it saves its data in the RED database
This means every time my program saves a change to the DB, the build process will overwrite the red DB with a fresh copy of the blue DB, next time the build process runs
So, every time I start the app, previous modified database is overwritten with a blank one
I can change this behavior if I click on the blue DB in solution explorer:
Copy always - always overwrites red db with blue db
Copy if newer - copy means db have same date, then your program edits red DB so it is newer, build process doesn't overwrite it.. If you make a change to the blue DB (add a table etc) then blue DB is newer, build will overwrite red db. This is a good setting to use
Copy never - you must manually copy the db
VS probably gave some info about this when you first added the DB, but the dialog it shows up is wordy and boring, so most people don't read it or don't really get what it's talking about even if they do read it:
Clicking Yes eventually causes you to ask a question like this on SO :) - no bad thing, but I do wish MS had made "Copy if Newer" the default..
Other notes about your code:
The topmost Sub BooksBindingNavigatorSaveItem_Click) is redundant - remove it
The btnAdd_Click method is nearly an identical re-statement of BooksBindingNavigatorSaveItem_Click_1 and is hence probably redundant - it should be removed. If you have two buttons intended to save data, put the save code into a sub and call it from both button click handlers; don't repeat yourself

Delete selected rows in datagridview from database

I'm trying to delete the rows which the user selects in a datagridview using SQL Server.
I have a datagridview that loads the contents of the database, in this case Username and Password.
Keep in mind that each username is unique in the database and so I should be able to delete each row using the unique username.
The SQL I currently have is DELETE FROM 'Users&Passwords' WHERE 'Username' = ? I'm not sure if this is entirely correct, however whenever I click QueryBuilder it seems to accept it.
The code I have to try and do this is as follows:
Private Sub btn_remove_Click(sender As Object, e As EventArgs) Handles btn_remove.Click
For Each row As DataGridViewRow In DataGridView1.SelectedRows
Dim usernametodelete As String = DataGridView1.SelectedRows(0).Cells(0).Value.ToString
'TextBox1.Text += usernametodelete
Me.Users_PasswordsTableAdapter.DeleteUser(usernametodelete)
Me.Users_PasswordsTableAdapter.Fill(Me.ManageUsersDataSet._Users_Passwords)
Next
End Sub
I would like that when the user clicks the Remove User(s) button the selected rows from the datagridview remove the rows from the database. Any help would be greatly appreciated.
You're getting slightly more involved than you need to. The set of steps you'd ideally take would be:
0) rename your table so it doesn't have an & character in it - it's just asking for trouble
1) Add your table to your dataset with something like this process: right click the design surface, new tableadapter, configure the connection string, set the query as SELECT * FROM Users WHERE Username LIKE #username, ensure other things are set, like whether you want generate dbdirect methods, and whether you want the dataset to refresh new values
2) In your data sources window (might not be showing by default, find it in on of visual studio's menus) drag and drop the Users node from the data soruces window, out onto the form. This will create a datagridview bound to the typed datatable, and also create a dataset, tableadapter, tableadaptermanager (not strictly needed; can delete), a bindingnavigator tool strip (again not strictly needed but has a handy pre-wired Save button on it) and a bindingsource. It will also pre-fill some code into the form_load event handler to fill the datatable
3) That's it - your form has a grid, bound to a datatable. That grid is capable of deleting rows - click the row header and press the delete button on the keyboard, row disappears. Click the save icon in the toolstrip, and the change is persisted to the database. The only thing you have to do is get data into the table in the first place. I gave a SQL that allows you to choose some usernames to load, but you can easily make it load the whole lot by changing the line of code in Form_Load to:
yourTableAdapterName.Fill(yourDatasetname.YourDatatableName, "%")
Passing a percent as the name is like a * wildcard in DOS. LIKE % will select all records. You can also, of course, leave the default provision (it will reference a textbox on the toolstrip) and instead run the program, put a % in the textbox on the toolstrip and click Fill. Or you can put JOHNSMITH, or JOHN% in th textbox and fill, to load that user/those users respectively
Hopefully you already did 1 and 2..
A bit of a background story on how all this stuff works:
DataTables are client side representations of tables in the database. It isn't intended that they contain all the data in the database, only a portion of this that you want to work with. When you load a row from the DB you can edit it, delete it (mark as deleted) and when you call tableAdapter.Update(yourtable) th changes you made are persisted to the DB. Note that even though it's called Update, the method will save new rows (by doing an INSERT), deleted rows (SQL DELETE) and make updates (SQL UPDATE). If your datatable has 4 rows laodd from the DB, and you then add 2 new rows, make changes to 3 of the loaded rows and delete the 4th row, then calling tableadapter.Update will save all these changes to the DB. You aren't required to pick through your datatable, calling tableadapter.insert/update/delete accordingly, to manually persist these changes. The flow of using a tableadapter is thus:
tableAdapter.Fill(datatable, maybe,parameters,to,control,the,fill,here)
'work with the datatable here, change, insert, delete. Use loops/code, use the UI, etc
tableAdapter.Update(datatable) 'save changes
I suggest putting an id column in your datagridview and just hide it so that you can easily delete the record you want to remove easily without conflict, because if you will use a username, what if theres a duplicate username exist.
Private Sub BTNDELETE_Click(sender As Object, e As EventArgs) Handles BTNDELETE.Click
Public result As Integer = 0
Public cmd As New MySqlCommand
strcon.Open() 'your connection string here
With cmd
.Connection = strcon 'your connection string
.CommandText = "DELETE FROM `users` WHERE `id` = '" & DTGLIST.CurrentRow.Cells(0).Value.ToString() & "';"
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("Successfully Removed.", MsgBoxStyle.Information, "Info")
DTGLIST.Rows.Remove(DTGLIST.SelectedRows(0))
End If
End With
strcon.Close() 'close the connection string
End Sub
Managed to figure out why my delete query wasn't working a few days ago. It was due to my SQL not being correct. This worked for me DELETE FROM [Users&Passwords] WHERE (Username = ?).
Also having the line Me.Users_PasswordsTableAdapter.DeleteUser(usernametodelete) in my code made it work.

VB .net Clickonce - check for update but dont update

ok so ive got an updating program via clickonce, I want it to notify the user there is an update but don't actually update the program until an admin logs on and requests the update to go ahead.
I'm checking for updates like this via code
If My.Application.IsNetworkDeployed() Then
If My.Application.Deployment.CheckForUpdate() Then
MsgBox("Updates are available", vbInformation, "Updates available")
Note I haven't called the
My.Application.Deployment.Update()
to actually update.
When my application checks for updates it displays ok, but when no one does anything else when it is shut down again and then started up - it seems to revert back to automatically downloading the update on program startup. I have update automatically turned off in the project properties
I tried not checking for updates and the program starts and doesn't update so I'm thinking that just the act of checking and finding an update automatically sets the program to download it next time its started. which id rather it didn't
has anyone come across this issue before?
thanks
Modify this code. It is with an "updating" action but you'll be able to change this
Imports System.Deployment.Application
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim updateCheck = ApplicationDeployment.CurrentDeployment
Dim info = updateCheck.CheckForDetailedUpdate()
If (info.UpdateAvailable) Then
MsgBox("Update wird geladen.")
updateCheck.Update()
MessageBox.Show("The application has been upgraded, and will now restart.")
Application.Restart()
End If
Catch : End Try
Form1.Show()
Me.Close()
End Sub
Do you by any chance have these options selected??
If you're handling the updates programmatically, you need to untick the "The application should check for updates" box.
Doing this will grey-out the "After" and "Before" radio buttons below it.