Вы находитесь на странице: 1из 8

For me, I dont like using the tools VS provides that write your databse code for you.

I prefer to write all my code out that does my Inserts, Updates, Adding and Deleting values to the database. Also, anytime youre using OleDB, or SQL or any type of connection be sure you import the namespace you will be needing. For OleDB we will be using Imports System.Data.OleDb Form 1(frmMain) - The Main Form btnNew - New Record Button btnUpdate - Update Record Button btnDelete - Delete Record Button dgv1 - DataGridView for Records txtSearch - Search Records

First to connect to any Database source you have to setup your connection string. I usually go with Access or SQL Server. If you are looking into using another datasource check out www.connectionstrings.com for other data sources like MySQL, Oracle and lots more.
1 Imports System.Data.OleDb 2 Public Class frmMain 3 4 ' Our Connection String - Be sure you change the Data Source Dim con1 As New OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=C:\Users\Sethro\Desktop\Test.mdb")

Now we go into selecting our records from the Data Source and populating out DataGridView with them.
0 ' This displays our records in the DataGridView so the User can 1 select them to update, delete, or search 0 Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As Syst 2 em.EventArgs) HandlesMyBase.Load 03 04 05 ' Our SQL Statement Dim sql As String

sql = "SELECT * FROM users" ' This is our DataAdapter. This executes our SQL Statement above 06 against the Database 07 08 09 10 11 12 13 14 15 16 17 18 ' we defined in the Connection String Dim adapter As New OleDbDataAdapter(sql, con1) ' Gets the records from the table and fills our adapter with those. Dim dt As New DataTable("users") adapter.Fill(dt) ' Assigns our DataSource on the DataGridView dgv1.DataSource = dt ' Dim sql1 As String sql1 = "SELECT * FROM users" Dim adapter1 As New OleDbDataAdapter(sql1, con1) Dim cmd1 As New OleDbCommand(sql1, con1)

19 20 21 22 23 24

'Dim dt1 As New DataTable("users") con1.Open() Dim myreader As OleDbDataReader = cmd1.ExecuteReader myreader.Read() con1.Close()

25 End Sub

Now that we have our records, and an application to interact with our database, we dont have to open the data file and edit it. We can show the New Record form and we can add records from it. The code to the New Record form(Form2) is below. We also have our update button and delete button. With our Update it allows us to select a record from the DataGridView, then we can click the Update button and the Update Record form shows with the corresponding information from the selected row in the DataGridView. You can also double click the record and it will open the Update Record form with the corresponding information.
0 Private Sub btnNew_Click(ByVal sender As System.Object, ByVal e As S 1 ystem.EventArgs) HandlesbtnNew.Click 0 2 Shows the New Record form(Form2) 03 04 0 5 Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e 0 6 As System.EventArgs)Handles btnUpdate.Click 07 frmUpdate.Show() ' What this does is when the User selects a record in the 08 DataGridView ' it will populate the textbox on the other form with the corresponding 10 ' Cell Value. 09 frmUpdate.txtFirst.Text = dgv1.CurrentRow.Cells(0).Value.ToString frmUpdate.txtLast.Text = 12 dgv1.CurrentRow.Cells(1).Value.ToString 11 frmUpdate.txtAddress.Text = dgv1.CurrentRow.Cells(2).Value.ToString frmUpdate.txtCity.Text = 14 dgv1.CurrentRow.Cells(3).Value.ToString 13 frmUpdate.txtZip.Text = dgv1.CurrentRow.Cells(4).Value.ToString frmUpdate.txtPhone.Text = 16 dgv1.CurrentRow.Cells(5).Value.ToString 15 frmUpdate.txtEmail.Text = dgv1.CurrentRow.Cells(6).Value.ToString frmUpdate.txtID.Text = 18 dgv1.CurrentRow.Cells(7).Value.ToString 17 frmNew.Show() End Sub

19 20

End Sub

Private Sub dgv1_CellDoubleClick(ByVal sender As Object, ByVal e As 2 1 System.Windows.Forms.DataGridViewCellEventArgs) Handles dgv1.CellDoub leClick 2 frmUpdate.Show() 2 ' Same thing as btnUpdate_Click except the user can actually DoubleClick ' a record. You want to be sure you get the field names and 24 cell numbers 23 25 correct or the information will be misconstrued. frmUpdate.txtFirst.Text = 26 dgv1.Rows(e.RowIndex).Cells(0).Value.ToString frmUpdate.txtLast.Text = dgv1.Rows(e.RowIndex).Cells(1).Value.ToString frmUpdate.txtAddress.Text = 28 dgv1.Rows(e.RowIndex).Cells(2).Value.ToString 27 frmUpdate.txtCity.Text = dgv1.Rows(e.RowIndex).Cells(3).Value.ToString frmUpdate.txtZip.Text = 30 dgv1.Rows(e.RowIndex).Cells(4).Value.ToString 29 frmUpdate.txtPhone.Text = dgv1.Rows(e.RowIndex).Cells(5).Value.ToString frmUpdate.txtEmail.Text = 32 dgv1.Rows(e.RowIndex).Cells(6).Value.ToString 31 33 34 frmUpdate.txtID.Text = dgv1.Rows(e.RowIndex).Cells(7).Value.ToString End Sub

Below is the code for our Delete Record function. You are able to select a record and hit the Delete button and the record will be deleted from both the DataGridView and the data source file. Be sure you have a Unique ID or Field in your Data file so you can use the WHERE statement to be sure that the correct record is deleted.
Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e 0 1 As System.EventArgs) HandlesbtnDelete.Click 0 ' This is our DELETE Statement. To be sure we delete the correct 2 record and not all of 03 them. 04 05 06 07 ' We use the WHERE to be sure only that record that the user has selected is deleted. Dim sqldelete As String sqldelete = "DELETE * FROM users WHERE IDNum='" & dgv1.CurrentRow.Cells(7).Value.ToString &"'"

' This is our DataAdapter. This executes our SQL Statement above against the Database 08 ' we defined in the Connection String 09 Dim adapter As New OleDbDataAdapter(sqldelete, con1)

10 11 12 13

' Gets the records from the table and fills our adapter with those. Dim dt As New DataTable("users") adapter.Fill(dt)

' Assigns the edited DataSource on the DataGridView and the refreshes the 14 ' view to ensure everything is up to date in real time. 15 16 17 18 19 dgv1.DataSource = dt This is a Sub in Module 1 to refresh the DataGridView when information is added, updated, or deleted. RefreshDGV() End Sub

Now is the important part. When a user has a bunch of records they want to sort though they needto be able to Search for what they are looking for without having to browse through all the records. Below is the code for our Search function.
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByV 0 1 al e As System.EventArgs)Handles txtSearch.TextChanged 0 ' SQL Statement so our User can search for either FirstName 2 or LastName 03 Dim sqlsearch As String

sqlsearch = "SELECT * FROM users WHERE FirstName LIKE '%" & 04 txtSearch.Text & "%'" & " OR LastName LIKE '%" & txtSearch.Text & "%'" 05 06 07 08 09 10 11 12 ' Once again we execute the SQL statements against our DataBase Dim adapter As New OleDbDataAdapter(sqlsearch, con1) ' Shows the records and updates the DataGridView Dim dt As New DataTable("users") adapter.Fill(dt) dgv1.DataSource = dt ' End Sub

13 End Class

Now the code for the New Record Form to create new records. Form 2(frmNew) - New Record Form txtFirst txtLast txtAddress txtCity txtZip txtPhone txtEmail

txtID btnSave

1 Imports System.Data.Oledb 2 Public Class frmNew 3 4 ' Our Connection String Dim con1 As New OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=C:\Users\Sethro\Desktop\Test.mdb")

The Save button is what saves the new information to our Data source.
0 Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As 1 System.EventArgs) HandlesbtnSave.Click 0 Dim sqlinsert As String 2 We use the INSERT statement which tells our program to add the information 04 from the Forms Text fields into the Databases columns. 03 sqlinsert = "INSERT INTO users(FirstName, LastName, Address, City, Zip, Phone, Email, IDNum)" & _ "VALUES(@FirstName, @LastName, @Address, @City, @Zip, 06 @Phone, @Email, @IDNum)" 05 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 column cmd.Parameters.Add(New OleDbParameter("@FirstName", txtFirst.Text)) cmd.Parameters.Add(New OleDbParameter("@LastName", txtLast.Text)) cmd.Parameters.Add(New OleDbParameter("@Address", txtAddress.Text)) cmd.Parameters.Add(New OleDbParameter("@City", txtCity.Text)) cmd.Parameters.Add(New OleDbParameter("@Zip", txtZip.Text)) cmd.Parameters.Add(New OleDbParameter("@Phone", txtPhone.Text)) cmd.Parameters.Add(New OleDbParameter("@Email", txtEmail.Text)) cmd.Parameters.Add(New OleDbParameter("@IDNum", txtID.Text)) ' This is what actually writes our changes to the DataBase. ' You have to open the connection, execute the commands and ' then close connection. con1.Open() cmd.ExecuteNonQuery() con1.Close() ' This are subs in Module1, to clear all the TextBoxes on Dim cmd As New OleDbCommand(sqlinsert, con1) ' This assigns the values for our columns in the DataBase. ' To ensure the correct values are written to the correct

the form ' and refresh the DataGridView on the MainForm to show our new records. 26 ClearTextBox(Me) 25 27 28 29 RefreshDGV() Me.Close() End Sub

30 End Class

Now our code for the Update form to update any records. Form 3(frmUpdate) - Update Record Form txtFirst txtLast txtAddress txtCity txtZip txtPhone txtEmail txtID btnUpdate

1 Imports System.Data.Oledb 2 Public Class frmUpdate 3 4 ' Our Connection String Dim con1 As New OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=C:\Users\Sethro\Desktop\Test.mdb")

The code for the Update button.


Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e 0 1 As System.EventArgs)Handles btnUpdate.Click 0 Dim sqlupdate As String 2 Here we use the UPDATE Statement to update the information. To be sure we are updating the right record we also use the WHERE clause to 04 be sureno information 03 05 is added or changed in the other records sqlupdate = "UPDATE users SET FirstName=@FirstName, 06 LastName=@LastName, " & _ 07 08 09 10 "Address=@Address, City=@City, Zip=@Zip, Phone=@Phone, Email=@Email WHERE IDNum='" & txtID.Text & "'" Dim cmd As New OleDbCommand(sqlupdate, con1) ' This assigns the values for our columns in the DataBase. ' To ensure the correct values are written to the correct

column 11 12 13 14 15 16 17 cmd.Parameters.Add(New OleDbParameter("@FirstName", txtFirst.Text)) cmd.Parameters.Add(New OleDbParameter("@LastName", txtLast.Text)) cmd.Parameters.Add(New OleDbParameter("@Address", txtAddress.Text)) cmd.Parameters.Add(New OleDbParameter("@City", txtCity.Text)) cmd.Parameters.Add(New OleDbParameter("@Zip", txtZip.Text)) cmd.Parameters.Add(New OleDbParameter("@Phone", txtPhone.Text))

cmd.Parameters.Add(New OleDbParameter("@Email", txtEmail.Text)) 18 ' This is what actually writes our changes to the DataBase. 19 20 21 22 23 24 25 the form ' You have to open the connection, execute the commands and ' then close connection. con1.Open() cmd.ExecuteNonQuery() con1.Close() ' This are subs in Module1, to clear all the TextBoxes on

' and refresh the DataGridView on the MainForm to show our new records. 26 ClearTextBox(Me) 27 28 29 Me.Close() RefreshDGV() End Sub

30 End Class

Module 1 holds the code for the RefreshDGV and ClearTextBox Subs.
01 Imports System.Data.OleDb 02 Module Module1 0 Dim con1 As New OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0 3 ;Data Source=C:\Users\Sethro\Desktop\Test.mdb") 04 05 06 07 08 09 10 11 12 Sub RefreshDGV() Dim sql As String sql = "SELECT * FROM users" Dim adapter As New OleDbDataAdapter(sql, con1) Dim dt As New DataTable("users") adapter.Fill(dt) frmMain.dgv1.DataSource = dt End Sub

13 14 15 16 17 18 19

Sub ClearTextBox(ByVal FormName As Form) For Each txt As Control In FormName.Controls If TypeOf txt Is TextBox Then CType(txt, TextBox).Text = "" End If Next End Sub

20 End Module

Ive attached the project file so you can open it up and see all the action for yourself. [attachment=15608:attachment]

Вам также может понравиться