1. Buat layout seperti dibawah , tambahkan 3 label, 3 textbox, 1 Listview
2. Kemudian buat class
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();
}
}
}
3. Tambahkan sintax pada form dan button simpan
private void Form1_Load(object sender, EventArgs e)
{
listdata();
}
tambahkan sintak pada event klik button simpan :
private void btnSimpan_Click(object sender, EventArgs e)
{
if (txtNama.Text = "")
command.ExecuteNonQuery();{
MessageBox.Show("Nama tidak boleh kosong ");
txtNama.Focus():
}else if (txtKeterangan.Text = "")
{
MessageBox.Show("Keterangan tidak boleh kosong ");
txtKeterangan.Focus():
}
else {
System.Data.SqlClient.SqlConnection conn = GetConn();
conn.Open();
string sql = "insert into jenis values ('" + txtNama.Text + "','" + txtKeterangan.Text +"')";
SqlCommand command = new SqlCommand(sql, conn);
conn.Close();
MessageBox.Show("Pengisian Table Jenis Sukses Tersimpan");
}
}