This article helps you to insert the data in gridview, which performs several operations like, inserting, updating and deleting records from DB.
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(); } } |
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
No comments:
Post a Comment