Note: Put "using System.Data.SqlClient;" above the namespace to access sql server library.
//initialize all classes //Declare a variable string strquery; int res;
private void LoadRecords() { try { strquery = "SELECT ID, Firstname, Lastname,Address, ContactNo,EmailAdd FROM tbltest"; sql_cmd.Connection = strcon; sql_cmd.CommandText = strquery; sql_da.SelectCommand = sql_cmd; sql_da.Fill(dt); dataGridView1.DataSource = dt; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { sql_da.Dispose(); } }
//establish a connection between sql server 2005 express edition to c#.net strcon.ConnectionString = "Data Source=.\\SQLEXPRESS;Database=testdb;trusted_connection=true;"; //call a method to retrieve it on the first loa of the form LoadRecords();
try { strcon.Open(); strquery = "DELETE FROM tbltest WHERE ID=" + dataGridView1.CurrentRow .Cells[0].FormattedValue ; sql_cmd.Connection = strcon; sql_cmd.CommandText = strquery; int result = sql_cmd.ExecuteNonQuery(); if (res > 0) { MessageBox.Show("Data has been deleted in the SQL database"); LoadRecords (); } else { MessageBox.Show("SQL QUERY ERROR"); } strcon.Close(); } catch (Exception ex)//catch exeption { MessageBox.Show(ex.Message); }