OnRowDeleting="GridView1_RowDeleting">
Default.aspx.cs
using System;
using System.Data;
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;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
bindData();
}
private void bindData()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
SqlCommand cmd = new SqlCommand("select id,name from employee", con);
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bindData();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
if (e.RowIndex != -1)
{
int id = (int)GridView1.DataKeys[e.RowIndex].Value;
TextBox txt1 = (TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0];
string str1 = txt1.Text;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString()))
{
string sql = "UPDATE employee " + "SET name='" + str1 + "' " + "WHERE id= " + GridView1.DataKeys[e.RowIndex].Value;
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
GridView1.EditIndex = -1;
bindData();
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bindData();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = (int)GridView1.DataKeys[e.RowIndex].Value;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString()))
{
string sql = "Delete From employee Where id=@id";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("@id", id);
cmd.ExecuteNonQuery();
con.Close();
bindData();
}
}
}
No comments:
Post a Comment