ADO.NET

ADO.NET Projects

ADO.NET Project 1

ADO.NET Examples

Examples

adplus-dvertising
How to update a table data in GridView Control Using C#
Previous Home Next
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection newConnection = new 
SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS;
initial catalog=newDatabase;integrated security=true;");
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
bindData();
}
public void bindData()
{
SqlCommand cmd = new SqlCommand
	("select * from emp_tbl", newConnection);
newConnection.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
GridView1.DataSource = dr;
GridView1.DataBind();
}
newConnection.Close();
}
protected void GridView1_RowEditing
	(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bindData();
}
protected void Button1_Click(object sender, EventArgs e)
{
newConnection.Open();
SqlCommand cmdd = new 
SqlCommand("update emp_tbl set nme=@a,age=@b
where emp_id='"+TextBox3.Text+"'", newConnection);
cmdd.Parameters.Add("@a",TextBox1.Text);
cmdd.Parameters.Add("@b", TextBox2.Text);
cmdd.ExecuteNonQuery();
newConnection.Close();
bindData();
}
protected void GridView1_RowUpdating
	(object sender, GridViewUpdateEventArgs e)
{
string s = GridView1.DataKeys[e.RowIndex].Value.ToString();

newConnection.Open();
SqlCommand cmdd = new 
SqlCommand("select * from emp_tbl where emp_id='" + s 
	+ "'", newConnection);
SqlDataReader dr1 = cmdd.ExecuteReader();
if (dr1.Read())
{
TextBox1.Text = dr1["nme"].ToString();
TextBox2.Text = dr1["age"].ToString();
TextBox3.Text = dr1["emp_id"].ToString();
}
newConnection.Close();
}
protected void GridView1_RowCancelingEdit
	(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bindData();
}
}

OutPut:

Click on the Edit Button which row you wado.net to update.

Click on the Update Button.

Edit your Values and click on Update, value is Updated.

Previous Home Next