Users Pricing

articles

home / developersection / articles / insert, update and delete data in gridview using the sql database

Insert, Update and Delete data in GridView using the SQL Database

mohan kumar 15534 02 May 2012 Updated 24 Nov 2019

This article helps you to insert the data in gridview, which performs several operations like, inserting, updating and deleting records fromDB.Insert, Update and Delete data in GridView using the SQL Database

Code Behind Code is as follows:-

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page {     SqlConnection con = new SqlConnection("server=.;database=db;uid=sa;pwd=wintellect");     SqlDataAdapter da;     SqlCommand cmd;     DataSet ds= new DataSet();     SqlDataReader dr;     protected void Page_Load(object sender, EventArgs e)     {       if (!IsPostBack)       {        show();       }     }     public void show()     {       da = new SqlDataAdapter("select * from employee", con);       da.Fill(ds);       GridView1.DataSource = ds;       GridView1.DataBind();      } }
<![if !supportLineBreakNewLine]> 
<![endif]>

Code for Inserting Records:-


protected void Button1_Click(object sender, EventArgs e) {     string str = "insert into employee values(@emp_id,@emp_name,@emp_salary)";     cmd = new SqlCommand(str, con);     cmd.Parameters.AddWithValue("@emp_id", TextBox1.Text);     cmd.Parameters.AddWithValue("@emp_name", TextBox2.Text);     cmd.Parameters.AddWithValue("@emp_salary", TextBox3.Text);     con.Open();     cmd.ExecuteNonQuery();     con.Close();     show();     Response.Write("Record Inserted"); }

Code for Updating Records:-


protected void Button2_Click(object sender, EventArgs e) {     string str = "update employee set emp_name=@emp_name,emp_salary=@emp_salary where emp_id=@emp_id";     cmd = new SqlCommand(str, con);     cmd.Parameters.AddWithValue("@emp_id", TextBox1.Text);     cmd.Parameters.AddWithValue("@emp_name", TextBox2.Text);     cmd.Parameters.AddWithValue("@emp_salary", TextBox3.Text);     con.Open();     dr = cmd.ExecuteReader();     con.Close();     show();     Response.Write("Record Updated");
}

Code for Deleting Records:-

protected void Button3_Click(object sender, EventArgs e) {     string str = "delete from employee where emp_id=@emp_id";     cmd = new SqlCommand(str, con);     cmd.Parameters.AddWithValue("@emp_id", TextBox1.Text);     con.Open();     dr = cmd.ExecuteReader();     con.Close();     show();     Response.Write("Record Deleted");
}

 Hope, this article helps for beginners. J




mohan kumar

Other

Having around 5 Years experience in .NET domain.


2 Comments