How to insert update delete data from database using c#.
1862
28-Sep-2016
I want to insert update delete data from database using c#.please help me.
Anonymous User
28-Sep-2016using 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; using System.Configuration; namespace testing_all_controls { public partial class Gridviewes : System.Web.UI.Page { SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { filldata(); } } private void filldata() { string sqlrt = ""; sqlrt = "select id,name,age from test"; cn.Open(); SqlDataAdapter da = new SqlDataAdapter(sqlrt, cn); DataSet dt = new DataSet(); da.Fill(dt); if (dt.Tables[0].Rows.Count == 0) { DataRow dr = dt.Tables[0].NewRow(); dr["id"] = "No Record"; dr["name"] = "No Record"; dr["Age"]="No Record"; dt.Tables [0].Rows .Add (dr); } GridView1.DataSource = dt; GridView1.DataBind(); cn.Close(); } protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Add") { TextBox txtname = (TextBox)GridView1.FooterRow.FindControl("txtname") as TextBox; TextBox txtage = (TextBox)GridView1.FooterRow.FindControl("txtage") as TextBox; string sqlrt = "insert into test(id,name,age) values('" + Guid.NewGuid().ToString().Substring(1, 6) + "','" + txtname.Text + "','" + txtage.Text + "')"; SqlCommand cmd = new SqlCommand(); cn.Open(); cmd.CommandText = sqlrt; cmd.Connection = cn; cmd.ExecuteNonQuery(); cn.Close(); filldata(); } if (e.CommandName == "Change") { int index = Convert.ToInt32(e.CommandArgument.ToString()); GridView1.EditIndex = index; filldata(); } if (e.CommandName == "Cancels") { GridView1.EditIndex = 0; filldata(); } if (e.CommandName == "Save") { int index = Convert.ToInt32(e.CommandArgument.ToString()); TextBox txtname = (TextBox)GridView1.Rows[index].FindControl("txtename") as TextBox; TextBox txtage = (TextBox)GridView1.Rows[index].FindControl("txteage") as TextBox; string id=Convert .ToString ( GridView1.DataKeys[index ].Value ); string sqlrt = "update test set name='" + txtname.Text + "',age='" + txtage.Text + "' where id='"+id+"'"; SqlCommand cmd = new SqlCommand(); cn.Open(); cmd.CommandText = sqlrt; cmd.Connection = cn; cmd.ExecuteNonQuery(); cn.Close(); GridView1.EditIndex =-1; filldata(); } if (e.CommandName == "Remove") { int index = Convert.ToInt32(e.CommandArgument.ToString()); string id=Convert .ToString ( GridView1.DataKeys[index ].Value ); string sqlrt = "delete from test where id='"+id+"'"; SqlCommand cmd = new SqlCommand(); cn.Open(); cmd.CommandText = sqlrt; cmd.Connection = cn; cmd.ExecuteNonQuery(); cn.Close(); filldata(); } } } }