Source Code
Source Code
Imports System.Data.SqlClient Imports System.Data Module Module1 Public constrg As String = "Data source=.\sqlexpress;Initial Catalog=latihan;integrated security=true" Public koneksi As SqlConnection Public perintah As SqlCommand Public da As SqlDataAdapter Public dr As SqlDataReader Public Function buka() As SqlConnection Try koneksi = New SqlConnection(constrg) If koneksi.State <> ConnectionState.Closed Then koneksi.Close() koneksi.Open() Catch ex As Exception MsgBox(Err.Description.ToString()) End Try Return koneksi End Function Public Function tutup() As SqlConnection Try koneksi = New SqlConnection(constrg) If koneksi.State <> ConnectionState.Open Then koneksi.Close() koneksi.Close() Catch ex As Exception MsgBox(Err.Description.ToString()) End Try Return koneksi End Function End Module
'delete data Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click buka() kata = "delete from person where name='" & TextBox2.Text & "'" perintah = New SqlCommand(kata, koneksi) Dim i As Integer = perintah.ExecuteNonQuery Try If i = 1 Then MsgBox("data dihapus") isi() Else MsgBox("gagal") End If Catch ex As Exception MsgBox(Err.Description.ToString()) End Try End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load isi() End Sub 'Isi data grid Sub isi() buka() ds.Clear() DataGridView1.Refresh() da = New SqlDataAdapter("select * from person", koneksi) da.Fill(ds, "person") dttable = ds.Tables("person") dtview.Table = dttable DataGridView1.DataSource = dtview settingkolom() End Sub 'settingan nama kolom Sub settingkolom() With DataGridView1 .Columns("Name").HeaderText = "Nama Orang" .Columns("addr").HeaderText = "Alamat" End With End Sub 'menampilkan data/pencarian dengan keypress Private Sub TextBox2_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress If Asc(e.KeyChar) = 13 Then buka() kata = "select * from person where name='" & TextBox2.Text & "'" perintah = New SqlCommand(kata, koneksi) dr = perintah.ExecuteReader While dr.Read = True TextBox1.Text = dr(1) End While Else Exit Sub End If End Sub 'pencarian dengan cara seleksi data grid Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged buka() ds.Clear() DataGridView1.Refresh() da = New SqlDataAdapter("select * from person where name like '" & TextBox2.Text & "%'", koneksi) da.Fill(ds, "person") dttable = ds.Tables("person") dtview.Table = dttable DataGridView1.DataSource = dtview settingkolom() End Sub 'kosongkan textbox Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click TextBox1.Clear() TextBox2.Clear() End Sub End Class