articles

Home / DeveloperSection / Articles / Insert Update Delete Records in CSharp .NET

Insert Update Delete Records in CSharp .NET

Anonymous User20128 16-Jul-2010

To Insert, Delete or Update record in database from form, first of all we have to be

connected to the database.

Example

 string strConnection = "Server=abc\\SQLEXPRESs;Database=Employee;Trusted_Connection=True";
      SqlConnection con = new SqlConnection(strConnection);
      con.Open();
      SqlDataAdapter da = new SqlDataAdapter("select * from
employee", con);
      DataSet ds = new DataSet();
      da.Fill(ds, "Employee");
      DataTable dt = ds.Tables["Employee"];
Insert Record

Inorder to insert record in the database, first of all we have to insert the record in

the DataSet, then we have to update the DataAdapter.

Example
DataRow dr = dt.Rows[count];
dr[0] = txtId.Text;
dr[1] = txtName.Text;
dr[2] = txtAddress.Text;



Now to update the database we have to update the DataSet. Before updating


records in DataSet , we have to create an object of SqlCommandBuilder and pass


DataAdapter as its argument.

Example


System.Data.SqlClient.SqlCommandBuilder cb;
cb = new System.Data.SqlClient.SqlCommandBuilder(da);
da.Update(ds, "Employee");
Update Record

To update record in database, first of all we have to update record in DataSet.

Example

DataRow dr = dt.Rows[count];
dr[0] = txtId.Text;
dr[1] = txtName.Text;
dr[2] = txtAddress.Text; 

Now we have to update the DataAdapter in order to make changes in the

database.

          Example               

      System Data SqlClient.SqlCommandBuilder cb;
      cb= new System.Data.SqlClient.SqlCommandBuilder(da);     
      da.Update(ds, "Employee");
Delete Record

To delete record from database, first of all we have to delete record

from DataSet then we have to update the DataAdapter.

Example
     System.Data.SqlClient.SqlCommandBuilder cb;
cb= new System.Data.SqlClient.SqlCommandBuilder(da);
 
//Checking whether user really want to delete record or the button is pressed accidently.
if (MessageBox.Show("Are you sure?""Warning"MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
      {
            dt.Rows[count].Delete();            
            MessageBox.Show("Recorddeleted");
            display();
            da.Update(ds, "Employee");
      }
 

Updated 04-Mar-2020
I am a content writter !

Leave Comment

Comments

Liked By