Hello All,
In ASP.NET some times u might require,clients to update data through GridView.Following is the code for updating any row through GridView.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(@"Server=SERVER\SQLEXPRESS;Initial Catalog=sampleDB;User=sa;password=sql2008");
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
public void BindData()
{
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from UserData", con);
DataTable ds = new DataTable("UserData");
da.Fill(ds);
Label1.Text=ds.Rows.Count.ToString();
GridView1.DataSource = ds;
GridView1.DataBind();
Session["UserData"] = ds;
}
catch (Exception ex)
{
Label1.Text = ex.Message.ToString();
}
finally
{
con.Close();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["UserData"];
//Update the values.
GridViewRow row = GridView1.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["UserName"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["FirstName"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["LastName"] = ((TextBox)(row.Cells[3].Controls[0])).Text;
GridView1.EditIndex = -1;
BindData1();
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally{}
}
private void BindData1()
{
GridView1.DataSource = Session["UserData"];
GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
}