Wednesday, August 18, 2010

Perform Editing and Deleting with GridView Control

Editing and Deleting with GridView Control
Follow the following steps
  • First you place a GridView Control on the web form.
  • Under Add/Edit Column window, add apropriate columns ( I have added BoundColumns) to display data. Set its DataField property too.
  • Set AutoGenerateEditButton and AutoGenerateDeleteButton property into true.
  • Set GridView's apropriate events.
I have used Employee table to demonstrate this example. It has EmpId, Name, JobTitile and Salary columns.

public partial class GridViewAllCode : System.Web.UI.Page

{
SqlConnection con;
SqlCommand cmd;
DataTable dt;
SqlDataAdapter adp;


protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename="+Server.MapPath("App_Data")+"\\jobin.mdf"+";Integrated Security=True;User Instance=True");
con.Open();
cmd = new SqlCommand();
cmd.Connection = con;
if (!IsPostBack)
BindGrid();
}


private void BindGrid()
{
adp = new SqlDataAdapter("select * from Employee", con);
dt = new DataTable("Emp");
adp.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}


protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}


protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex =-1;
BindGrid();
}


protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int empId = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
string name=((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string jobTitle=((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
int salary = int.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text);
cmd.CommandText = "update Employee set Name='" + name + "', JobTitle='" + jobTitle + "', Salary=" + salary + " where EmpId=" + empId;
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
BindGrid();
}


protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int empId = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
cmd.CommandText = "delete Employee where EmpId=" + empId;
cmd.ExecuteNonQuery();
BindGrid();
}
}

No comments: