Percobaan #1 – Insert Data Menambahkan data dari textbox ke datagridview (dgv), kemudian menyimpan data pada dgv ke dalam tabel (database). Database yang digunakan MySQL. using System; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace CobaDataGridView { public partial class Form1 : Form { MySqlConnection conn; MySqlCommand cmd = new MySqlCommand(); public Form1() { InitializeComponent(); } private void btnTambah_Click(object sender, EventArgs e) { string rek = textBox1.Text; string uid = "1"; string[] row = {rek, uid}; //inisialisasi datagridview dataGridView1.ColumnCount = row.Length; dataGridView1.Columns[0].Name = "Rekening"; dataGridView1.Columns[1].Name = "UID"; dataGridView1.Rows.Add(row); textBox1.Text = ""; } private void button1_Click(object sender, EventArgs e) { Close(); } private void btnSimpan_Click(object sender, EventArgs e) { conn = new MySqlConnection("Server=127.0.0.1;Port=3306;UID=root;PWD=rahasia;Database=ujicoba;Allow User Variables=True"); conn.Open(); cmd.Connection = conn; cmd.CommandText = "INSERT INTO rekening(`rekening`,`uid`) VALUES(@rekening,@uid)"; cmd.Parameters.Add("@rekening", MySqlDbType.VarChar); cmd.Parameters.Add("@uid", MySqlDbType.Int32); for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) { cmd.Parameters[0].Value = dataGridView1.Rows[i].Cells[0].Value; cmd.Parameters[1].Value = dataGridView1.Rows[i].Cells[1].Value; cmd.ExecuteNonQuery(); } conn.Close(); dataGridView1.Rows.Clear(); } } } Percobaan #2 – Double Insert Data Menambahkan data user dan rekening (bisa lebih dari satu). Jika ada perubahan, karena scope dan menghindari error. using System; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace CobaDataGridView { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnTambah_Click(object sender, EventArgs e) { string rek = textBox1.Text; //string uid = "1"; //string[] row = {rek, uid}; //inisialisasi datagridview dataGridView1.ColumnCount = 1; dataGridView1.Columns[0].Name = "Rekening"; dataGridView1.Rows.Add(rek); textBox1.Text = ""; } private void button1_Click(object sender, EventArgs e) { Close(); } private void btnSimpan_Click(object sender, EventArgs e) { MySqlConnection conn = new MySqlConnection("Server=127.0.0.1;Port=3306;UID=root;PWD=rahasia;Database=ujicoba;Allow User Variables=True"); conn.Open(); MySqlCommand cmd = new MySqlCommand(); cmd.Connection = conn; //proses simpan data user cmd.CommandText = "INSERT INTO users(`nama`) VALUES(@nama)"; cmd.Parameters.AddWithValue("@nama", txtNama.Text); cmd.ExecuteNonQuery(); int lastId = (int)cmd.LastInsertedId; //proses memasukkan data dgv ke tabel MySqlCommand cmd2 = new MySqlCommand(); cmd2.Connection = conn; cmd2.CommandText = "INSERT INTO rekening(`rekening`,`uid`) VALUES(@rekening,@uid)"; cmd2.Parameters.Add("@rekening", MySqlDbType.VarChar); cmd2.Parameters.Add("@uid", MySqlDbType.Int32); for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) { string rek = dataGridView1.Rows[i].Cells[0].Value.ToString(); MessageBox.Show(rek); cmd2.Parameters[0].Value = rek; cmd2.Parameters[1].Value = lastId; cmd2.ExecuteNonQuery(); } conn.Close(); txtNama.Text = ""; dataGridView1.Rows.Clear(); } } } Percobaan #3 – Hapus dan Edit Data DGV Percobaan berikutnya adalah menghapus dan mengedit data pada DGV. Mode seleksi DGV adalah RowHeaderSelect yang artinya adalah ketika kita klik pada cell DGV berarti memilih seluruh cell pada baris tersebut. DGV diberikan event CellClick. Peringatan: proses ini satu arah menyimpan ke tabel (database) BUKAN sebaliknya. Data pada DGV HANYA dapat di-edit / di-hapus sebelum tersimpan ke dalam database. using System; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace CobaDataGridView { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnTambah_Click(object sender, EventArgs e) { string rek = textBox1.Text; //inisialisasi datagridview dataGridView1.ColumnCount = 1; dataGridView1.Columns[0].Name = "Rekening"; if (btnTambah.Text == "Update") { //update dataGridView1.Rows[baris].Cells[0].Value = rek; btnTambah.Text = "Tambah"; } else { //tambah dataGridView1.Rows.Add(rek); } textBox1.Text = ""; } private void button1_Click(object sender, EventArgs e) { Close(); } private void btnSimpan_Click(object sender, EventArgs e) { MySqlConnection conn = new MySqlConnection("Server=127.0.0.1;Port=3306;UID=root;PWD=rahasia;Database=ujicoba;Allow User Variables=True"); conn.Open(); MySqlCommand cmd = new MySqlCommand(); cmd.Connection = conn; //proses simpan data user cmd.CommandText = "INSERT INTO users(`nama`) VALUES(@nama)"; cmd.Parameters.AddWithValue("@nama", txtNama.Text); cmd.ExecuteNonQuery(); int lastId = (int)cmd.LastInsertedId; //MessageBox.Show(dataGridView1.Rows.Count.ToString()); //proses memasukkan data dgv ke tabel MySqlCommand cmd2 = new MySqlCommand(); cmd2.Connection = conn; cmd2.CommandText = "INSERT INTO rekening(`rekening`,`uid`) VALUES(@rekening,@uid)"; cmd2.Parameters.Add("@rekening", MySqlDbType.VarChar); cmd2.Parameters.Add("@uid", MySqlDbType.Int32); for (int i = 0; i < dataGridView1.Rows.Count; i++) { string rek = dataGridView1.Rows[i].Cells[0].Value.ToString(); //MessageBox.Show(rek); cmd2.Parameters[0].Value = rek; cmd2.Parameters[1].Value = lastId; cmd2.ExecuteNonQuery(); } conn.Close(); txtNama.Text = ""; dataGridView1.Rows.Clear(); } int baris = 0; private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { baris = dataGridView1.CurrentCell.RowIndex; textBox1.Text = dataGridView1.Rows[baris].Cells[0].Value.ToString(); btnHapus.Enabled = true; btnTambah.Text = "Update"; } private void btnHapus_Click(object sender, EventArgs e) { //hapus data dataGridView1.Rows.RemoveAt(baris); dataGridView1.Refresh(); textBox1.Text = ""; btnHapus.Enabled = false; } private void Form1_Load(object sender, EventArgs e) { btnHapus.Enabled = false; } } } Percobaan #4 – CRUD Database Percobaan ini adalah menampilkan detil data user beserta nomor rekening yang dimilikinya. Form user tidak akan dibahas karena HANYA menampilkan DGV yang apabila CellClick akan menampilkan form tambah data ini dalam mode View (menampilkan detil data user). Pada percobaan ini, ditambahkan fitur untuk Update data user dan rekening (edit, hapus, dan tambah rekening) yang dimilikinya. DGV rekening akan mengalami sedikit perubahan dengan penambahan kolom idrek (disembunyikan). Form2 Form ini dijadikan form yang pertama kali dijalankan. Form ini hanya menampilkan DGV dan 2 tombol. Tombol tambah akan membuka Form1 ke dalam mode insert. Sedangkan mode edit didapat ketika dobel-klik pada data yang tampil di DGV. Tombol Tutup, ya hanya untuk menutup form. Form1 ditampilkan dalam mode ShowDialog. using MySql.Data.MySqlClient; using System; using System.Data; using System.Windows.Forms; namespace CobaDataGridView { public partial class Form2 : Form { public static bool isEdit = false; public static int uid; MySqlConnection conn = new MySqlConnection("Server=127.0.0.1;Port=3306;UID=root;PWD=rahasia;Database=ujicoba;Allow User Variables=True"); public Form2() { InitializeComponent(); } public void Tampil() { try { conn.Open(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM users", conn); DataSet ds = new DataSet(); //membuat data set da.Fill(ds); //mengisi data set dari Data Adapter dataGridView1.DataSource = ds.Tables[0]; //mengisi data grid conn.Close(); //menutup koneksi //atur tampilan dataGridView1.Columns[0].Visible = false; //kolom ID dataGridView1.Columns[1].Width = 150; //atur lebar kolom time-date } catch (Exception) { MessageBox.Show("Ada error!"); } } private void Form2_Load(object sender, EventArgs e) { //tampilkan data di DGV Tampil(); } private void button1_Click(object sender, EventArgs e) { Close(); } private void button2_Click(object sender, EventArgs e) { isEdit = false; Hide(); using (Form1 form1 = new Form1()) form1.ShowDialog(); Show(); Tampil(); } private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { isEdit = true; uid = (int)dataGridView1.Rows[e.RowIndex].Cells[0].Value; //e.RowIndex //dataGridView1.Rows[baris].Cells[0].Value.ToString(); //MessageBox.Show("Tampilkan Form1 dalam mode edit"); Hide(); using (Form1 form1 = new Form1()) form1.ShowDialog(); Show(); Tampil(); } } } Form1 Form ini difungsikan untuk INSERT, EDIT dan DELETE data. Insert, berarti menambahkan data baru, baik data User dan Rekening-nya. Edit, berarti meng-edit data user dan rekening-nya. Khusus edit rekening adalah dengan meng-klik pd data rekening yang tampil di DGV. o Edit rekening yang ada o Insert rekening baru o Delete rekening yang dipilih using System; using System.Data; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace CobaDataGridView { public partial class Form1 : Form { int uid; int rid; int baris = 0; bool editMode = Form2.isEdit; MySqlConnection conn = new MySqlConnection("Server=127.0.0.1;Port=3306;UID=root;PWD=rahasia;Database=ujicoba;Allow User Variables=True"); MySqlCommand cmd = new MySqlCommand(); MySqlCommand cmd2 = new MySqlCommand(); public Form1() { InitializeComponent(); } private void btnTambah_Click(object sender, EventArgs e) { string rek = textBox1.Text; if (editMode && btnTambah.Text == "Update") { dataGridView1.Rows[baris].Cells[1].Value = rek; btnTambah.Text = "Tambah"; } else if(editMode && btnTambah.Text == "Tambah") { //karena data dari database maka harus ditambahkan ke DataTable-nya DataTable dt = dataGridView1.DataSource as DataTable; dt.Rows.Add(0, rek, uid); dataGridView1.DataSource = dt; } else if(!editMode && btnTambah.Text == "Update") { //update //inisialisasi datagridview dataGridView1.ColumnCount = 1; dataGridView1.Columns[0].Name = "Rekening"; dataGridView1.Rows[baris].Cells[0].Value = rek; btnTambah.Text = "Tambah"; } else { //tambah //inisialisasi datagridview dataGridView1.ColumnCount = 1; dataGridView1.Columns[0].Name = "Rekening"; dataGridView1.Rows.Add(rek); } textBox1.Text = ""; } private void button1_Click(object sender, EventArgs e) { Close(); } private void btnSimpan_Click(object sender, EventArgs e) { conn.Open(); cmd.Connection = conn; if (editMode) { int uid = Form2.uid; // edit mode cmd.CommandText = "UPDATE users SET `nama`=@nama WHERE `id`=@uid"; cmd.Parameters.AddWithValue("@nama", txtNama.Text); cmd.Parameters.AddWithValue("@uid", uid); cmd.ExecuteNonQuery(); //update juga data rekening cmd2.Connection = conn; cmd2.CommandText = "INSERT INTO rekening(`id`,`rekening`,`uid`) VALUES(@rid, @rekening, @uid) ON DUPLICATE KEY UPDATE `rekening`=@rekening"; cmd2.Parameters.Add("@rekening", MySqlDbType.VarChar); cmd2.Parameters.Add("@rid", MySqlDbType.Int32); cmd2.Parameters.Add("@uid", MySqlDbType.Int32); for (int i = 0; i < dataGridView1.Rows.Count; i++) { string rek = dataGridView1.Rows[i].Cells[1].Value.ToString(); int xid = (int)dataGridView1.Rows[i].Cells[0].Value; cmd2.Parameters[0].Value = rek; cmd2.Parameters[1].Value = xid; cmd2.Parameters[2].Value = uid; cmd2.ExecuteNonQuery(); } dataGridView1.DataSource = null; btnSimpan.Text = "Simpan"; editMode = false; } else { //proses simpan data user cmd.CommandText = "INSERT INTO users(`nama`) VALUES(@nama)"; cmd.Parameters.AddWithValue("@nama", txtNama.Text); cmd.ExecuteNonQuery(); int lastId = (int)cmd.LastInsertedId; //ambil id user yg barusan ditambahkan //proses memasukkan data dgv ke tabel cmd2.Connection = conn; cmd2.CommandText = "INSERT INTO rekening(`rekening`,`uid`) VALUES(@rekening,@uid)"; cmd2.Parameters.Add("@rekening", MySqlDbType.VarChar); cmd2.Parameters.Add("@uid1", MySqlDbType.Int32); for (int i = 0; i < dataGridView1.Rows.Count; i++) { string rek = dataGridView1.Rows[i].Cells[0].Value.ToString(); cmd2.Parameters[0].Value = rek; cmd2.Parameters[1].Value = lastId; cmd2.ExecuteNonQuery(); } dataGridView1.Rows.Clear(); } cmd.Parameters.Clear(); cmd2.Parameters.Clear(); conn.Close(); txtNama.Text = ""; } private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { if (editMode) { //ambil id rekening rid = (int)dataGridView1.Rows[e.RowIndex].Cells[0].Value; textBox1.Text = dataGridView1.Rows[baris].Cells[1].Value.ToString(); baris = dataGridView1.CurrentCell.RowIndex; } else { baris = dataGridView1.CurrentCell.RowIndex; textBox1.Text = dataGridView1.Rows[baris].Cells[0].Value.ToString(); } btnHapus.Enabled = true; btnTambah.Text = "Update"; } private void btnHapus_Click(object sender, EventArgs e) { if(editMode) { DataTable dt = dataGridView1.DataSource as DataTable; DataRow dr = dt.Rows[baris]; dr.Delete(); if (rid > 0) { //jika rid > 0 berarti ada di database conn.Open(); cmd.Connection = conn; cmd.CommandText = "DELETE FROM rekening WHERE id=@rid"; cmd.Parameters.AddWithValue("@rid", rid); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); conn.Close(); } } else { //hapus data dataGridView1.Rows.RemoveAt(baris); dataGridView1.Refresh(); } textBox1.Text = ""; btnHapus.Enabled = false; btnTambah.Text = "Tambah"; //hapus belum berfungsi jika data diambil dari database } private void Form1_Load(object sender, EventArgs e) { btnHapus.Enabled = false; if(editMode) { uid = Form2.uid; //ambil data user dan rekenening-nya conn.Open(); string sql = "SELECT * FROM users WHERE id=" + uid + " LIMIT 1"; MySqlCommand cmdx = new MySqlCommand(sql, conn); MySqlDataReader dataReader = cmdx.ExecuteReader(); //button simpan HARUS diubah menjadi update? if (dataReader.Read()) { txtNama.Text = dataReader.GetString(1); dataReader.Close(); //tampilkan rekening di DGV MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM rekening WHERE uid=" + uid, conn); DataSet dataSet = new DataSet(); da.Fill(dataSet); dataGridView1.DataSource = dataSet.Tables[0]; dataGridView1.Columns[0].Visible = false; //dataGridView1.Columns[0].Width = 50; dataGridView1.Columns[1].Width = 150; //dataGridView1.Columns[2].Width = 50; dataGridView1.Columns[2].Visible = false; } conn.Close(); btnSimpan.Text = "Update"; } } } }