Data Controls
For understanding data controls design form like shown in below picture and take datagrid view control from toolbox. And add new database from solution explorer by choosing new item.
Add namespace
Imports System.Data.SqlClient
Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=
D:\Documents and Settings\R4R\My Documents\Visual Studio 2008\Projects\
WindowsFormsApplication14\WindowsFormsApplication14\r4r.mdf;Integrated
Security=True;User Instance=True")
Code for inserting Data in Database
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim com As New SqlCommand((((("insert into emp_detail values('"
+ textBox1.Text & "','") + textBox2.Text & "','") + textBox3.Text & "','")
+ textBox4.Text & "','") + textBox5.Text & "')", con)
con.Open()
com.ExecuteNonQuery()
con.Close()
End Sub
Code for viewing the total record in DataGridview by clicking the view button
Private Sub Button4_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button4.Click
Dim com2 As New SqlCommand("select * from emp_detail", con)
Dim da As New SqlDataAdapter(com2)
Dim ds As New DataSet()
con.Open()
da.Fill(ds, "emp_detail")
con.Close()
dataGridView1.DataSource = ds.Tables(0)
End Sub
Code for Updating the record from dataGrid View.
Private Sub Button2_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button2.Click
For Each row As DataGridViewRow In dataGridView1.SelectedRows
If row.Index <> dataGridView1.Rows.Count Then
id = dataGridView1.SelectedRows(0).Cells(0).Value.ToString()
Name = dataGridView1.SelectedRows(0).Cells(1).Value.ToString()
address = dataGridView1.SelectedRows(0).Cells(2).Value.ToString()
sal = dataGridView1.SelectedRows(0).Cells(3).Value.ToString()
cont = dataGridView1.SelectedRows(0).Cells(4).Value.ToString()
dataGridView1.Rows.RemoveAt(row.Index)
End If
Next
Dim com3 As New SqlCommand("update emp_detail set emp_name='"
& Name & "',emp_address='" & address & "',emp_sal='" & sal &
"',emp_cont='" & cont & "' where emp_id ='" & id & "'", con)
con.Open()
com3.ExecuteNonQuery()
con.Close()
End Sub
Code for Deleting the recording from Datagridview control
Private Sub Button3_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button3.Click
For Each row As DataGridViewRow In dataGridView1.SelectedRows
If row.Index <> dataGridView1.Rows.Count Then
id = dataGridView1.SelectedRows(0).Cells(0).Value.ToString()
dataGridView1.Rows.RemoveAt(row.Index)
End If
Next
Dim com3 As New SqlCommand("delete from emp_detail where emp_id ='" & id & "'", con)
con.Open()
com3.ExecuteNonQuery()
con.Close()
End Sub