BY USING ADO.NET
DataBase:
NAME = empLoyee.
TABLE:
NAME = empinfo.
FIELDS :
ID ( primary key ) ,Name ,FatherName,PhoneNo.
FORM:
4 TexBoxes 3 Buttons(insert ,update ,Delete).
INSERT:
We cannot insert data where primary key is set therefore for insertion we make textbox of id unvisible or leave .
private void INSERTBUTTON_CLICK(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=employee;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("select *from EmpInfo", cn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "Insert into EmpInfo(Name,FatherName,Phone no)VALUES( ' " +textBox1.Text + " ' , ' "+ textBox2.Text + " ' ," + textBox3.Text + " ) ";
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
MessageBox.Show("Record Saved");
}
ExecuteNonQuery Method:
The ExecuteNonQuery method of the SqlCommand class is used to execute commands that change a database. These commands include the Transact-SQL INSERT, UPDATE, DELETE, and SET statements. The method acts directly on a database connection and does not require a data set. It returns an integer that indicates the number of rows affected by the execution of a command. This method can also be used to perform catalog operations, such as querying the structure of a database or creating database objects.
UPDATE:
private void UPDATEBUTTON_CLICK(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=employee;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("select *from EMPINFO", cn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "update EMPINFO set Name = ' " + textBox2.Text + " ', Fathername = ' " + textBox3.Text + " ', phoneno = " + textBox4.Text + " where id = " + textBox1.Text + " ";
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
MessageBox.Show("Record Updated");
}
DELETE:
private void DELETEBUTTON_CLICK(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=employee;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("select *from empinfo", cn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "DELETE FROM EMPINFO WHERE STUID = " + textBox1.Text + " ";
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
MessageBox.Show("Record Deleted");
}