Wednesday, December 16, 2009

GridView --Editing and Deleting



A more easy way of editing and deleting a record in a grid view can be done as shown below.
A record could be edited within the grid view correspondingly reflecting the change in database

Sql connection and grid Binding

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

{
SqlConnection con = new SqlConnection(@"Data Source=KFJD-03843C5CB9\SQLEXPRESS;Initial Catalog=megha;Integrated Security=True");

public void gridbind()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from neme", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
con.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gridbind();
}
}

Insertion:_-------------------

protected void btnsav_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into neme (name,age,quali) values ('" + tbname.Text + "','" + tbage.Text + "','"+tbquali.Text+"')", con);
cmd.ExecuteNonQuery();
Response.Write("inserted");
con.Close();
gridbind();

}



Grid view Row updating, Editing and row cancel editing event--------------

gridbind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow gr = GridView1.Rows[e.RowIndex];
Label lbl = (Label)gr.FindControl("lbchk");
TextBox tb = (TextBox)gr.FindControl("tblchk");
TextBox tb2=(TextBox)gr.FindControl("tblchk1");
TextBox tb3=(TextBox)gr.FindControl("tbqualiedit");
con.Open();
SqlCommand cmd = new SqlCommand("update neme set name='" + tb.Text + "',age='"+tb2.Text+"',quali='"+tb3.Text+"' where id='" + lbl.Text + "'", con);
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
gridbind();

}


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

}


Deleting selected files-------------------------------

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

protected void lnkdel_Click(object sender, EventArgs e)
{
foreach (GridViewRow gr in GridView1.Rows)
{

Label lbl = (Label)gr.FindControl("lbchk");
CheckBox ch = (CheckBox)gr.FindControl("chk");

if (ch.Checked)
{
con.Open();
SqlCommand cmd = new SqlCommand("delete from neme where id='" + lbl.Text + "'", con);
cmd.ExecuteNonQuery();
con.Close();
gridbind();

}

}
}

No comments:

Post a Comment