Berikut adalah cara menghapus data pada Visual C#
1. Buat layout seperti ini :
TextBox3 = txtKeterangan
2. Tambahkan sintak class dan evnt
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace connectdatabase
{
class koneksi
{
public System.Data.SqlClient.SqlConnection GetConn()
{
System.Data.SqlClient.SqlConnection conn = newSystem.Data.SqlClient.SqlConnection();
conn.ConnectionString = "Data Source= localhost; Initial Catalog=dbdata;user=sa; Password=123456";
return conn;
}
}
}
public void listdata()
{
SqlDataReader reader = null;
lstView.Items.Clear();
lstView.Columns.Clear();
lstView.Columns.Add("ID", 70, HorizontalAlignment.Left);
lstView.Columns.Add("Nama", 150,HorizontalAlignment.Left);
lstView.Columns.Add("Keterangan", 150, HorizontalAlignment.Left);
lstView.GridLines = true;
lstView.FullRowSelect = true;
lstView.Activation = ItemActivation.TwoClick;
lstView.View = View.Details;
lstView.MultiSelect = false;
System.Data.SqlClient.SqlConnection conn = GetConn();
try
{
conn.Open();
string sql = "select * from jenis";
SqlCommand command = new SqlCommand(sql, conn);
command.ExecuteNonQuery();
// untuk menampung data dan menampilkan
reader = command.ExecuteReader();
while (reader.Read())
{
ListViewItem item = newListViewItem(reader["id"].ToString(), 0);
item.SubItems.Add(reader["nama"].ToString());
item.SubItems.Add(reader["keterangan"].ToString());
lstView.Items.Add(item);
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
finally
{
conn.Close();
}
}
}
Kemudian isikan pad form load, double klik list view dan event klik delete
private void Form1_Load(object sender, EventArgs e)
{
listdata();
}
private void lstView_MouseDoubleClick(object sender, MouseEventArgs e)
{
try
{
txtID.Text = lstView.SelectedItems[0].Text;
txtNama.Text =Convert.ToString(lstView.SelectedItems[0].SubItems[1].Text);
txtKeterangan.Text =Convert.ToString(lstView.SelectedItems[0].SubItems[2].Text);
}
catch
{
MessageBox.Show(e.ToString());
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
System.Data.SqlClient.SqlConnection conn = GetConn();
conn.Open();
string sql = "delete from jenis where id = '" + txtID.Text + "'";
SqlCommand command = new SqlCommand(sql, conn);
command.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Penghapusan data table jenis sukses");
}
Jalankan maka akan ditampilkan seperti gambar dibawah :