The program illustrate on how to connect C# to MsAcess database, retrieve records from the database and delete records from database.
Steps in searching and deleting records from Ms Access database.
1. Add oledb reference. using System.Data.OleDb;
2. Create object variables. (note: Make sure your object variables for connection and command are declared globally. OleDbConnection cn; //variable use for connecting the database
3. Create a connection string.
4. Inside the Form constructor instantiate your connection.
5. Inside the btnSearch_Click event create the statements for retrieving record from the database.
6. Inside the btnDelete_Click event create the statements for deleting record from the database.
string sql = @"DELETE from tblStudent where studentno = '" + txtID.Text + "'";
cm = new OleDbCommand(sql, cn);
OleDbCommand cm; //variable use for updating records
string connection = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\StudentRecord.accdb";
cn = new OleDbConnection(connection);
cn.Open();
string input = Interaction.InputBox("Look up", "Enter Student No.", "", 0, 0);
string sql = @"SELECT * from tblStudent where studentno like '" + input + "'";
cm = new OleDbCommand(sql, cn);
dr = cm.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
txtID.Text = dr.GetValue(0).ToString();
txtLname.Text = dr.GetString(1).ToString();
txtFname.Text = dr.GetString(2).ToString();
txtMI.Text = dr.GetString(3).ToString();
cboProgram.Text = dr.GetString(4).ToString();
}
else
{
MessageBox.Show("Student No. not exist!", "Searching Record",MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
dr.Close();
cm.ExecuteNonQuery();
MessageBox.Show("Record successfully deleted!", "Eraser Software Solution", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Clear();
Database: MS Access