CodeFile:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient ;
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;
public partial class GridBinding : System.Web.UI.Page
{
SqlConnection myConnection;
protected void Page_Load(object sender, EventArgs e)
{
myConnection = new SqlConnection("Trusted_Connection=true;DataBase=praveen_database");
if(!IsPostBack )
BindGrid();
}
public void BindGrid()
{
SqlDataAdapter da = new SqlDataAdapter("Select * from Table1", myConnection);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
public void Delete_GridViewDelete(object sender,GridViewDeleteEventArgs e)
{
SqlCommand cmd = new SqlCommand("Delete from Table1 Where Roll=@Roll", myConnection);
SqlParameter obj1 = new SqlParameter("@Roll", DbType.Int32 .ToString ());
obj1.Value = GridView1.Rows[e.RowIndex].Cells[3].Text ;
cmd.Parameters .Add (obj1 );
cmd.Connection.Open();
try
{
cmd.ExecuteNonQuery();
Label1.Text = "Record is deleted";
}
catch
{
Label1.Text = "Error";
}
cmd.Connection.Close();
BindGrid();
}
public void GridView_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
public void GridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGrid();
}
public void GridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlCommand cmd = new SqlCommand("Update table1 set Name=@Name,Address=@Address,Course=@Course,Roll=@Roll where Roll=@Roll", myConnection);
SqlParameter pa1 = new SqlParameter("@Name", DbType.StringFixedLength);
pa1.Value = ((TextBox)GridView1.Rows[e.RowIndex].Cells[0].Controls [0]).Text;
cmd.Parameters.Add(pa1);
SqlParameter pa2 = new SqlParameter("@Address", DbType.StringFixedLength);
pa2.Value = ((TextBox )GridView1.Rows[e.RowIndex].Cells[1].Controls [0]).Text;
cmd.Parameters.Add(pa2);
SqlParameter pa3 = new SqlParameter("@Course", DbType.StringFixedLength);
pa3.Value = ((TextBox )GridView1.Rows[e.RowIndex].Cells[2].Controls [0]).Text;
cmd.Parameters.Add(pa3);
SqlParameter pa4 = new SqlParameter("@Roll", DbType.Int32.ToString());
pa4.Value = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
cmd.Parameters.Add(pa4);
cmd.Connection.Open();
try
{
cmd.ExecuteNonQuery();
Label1.Text = "Record is updated";
GridView1.EditIndex = -1;
}
catch(Exception exc)
{
Label1.Text = exc.Message;
}
cmd.Connection.Close();
BindGrid();
}
}