Thursday, March 6, 2008

coding for update,edit,.delete in datagrid

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
{
SqlConnection con=new SqlConnection () ;
public void show()
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString;
SqlCommand cmd = new SqlCommand("select * from sample", con);
SqlDataAdapter dr = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dr.Fill(ds, "sample");
datagrid.DataSource = ds;
datagrid.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
show();
}
}
protected void datagrid_EditCommand(object source, DataGridCommandEventArgs e)
{
datagrid.EditItemIndex = e.Item.ItemIndex;
show();
}
protected void datagrid_CancelCommand(object source, DataGridCommandEventArgs e)
{
datagrid.EditItemIndex = -1;
show();
}
protected void datagrid_UpdateCommand(object source, DataGridCommandEventArgs e)
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString;
System.Web.UI.WebControls.TextBox txt = new System.Web.UI.WebControls.TextBox();
System.Web.UI.WebControls.TextBox txt1 = new System.Web.UI.WebControls.TextBox();
txt = (System.Web.UI.WebControls.TextBox)e.Item.Cells[3].Controls[0];
txt1 =(System.Web.UI.WebControls.TextBox)e.Item.Cells[4].Controls[0];
int i = Convert.ToInt16(txt1.Text.ToString());
Response.Write(txt.Text.ToString());
SqlCommand cmd = new SqlCommand("sp_updatedata1",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = txt.Text;
cmd.Parameters.Add("@num", SqlDbType.Int).Value = i;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
datagrid.EditItemIndex = -1;
show();
}
protected void datagrid_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Write("SELECTED NAME IS :"+datagrid.SelectedItem.Cells[3].Text.ToString ());
Response.Write("
SELECTED NO IS :"+datagrid.SelectedItem.Cells[4].Text.ToString());
}
protected void datagrid_DeleteCommand(object source, DataGridCommandEventArgs e)
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString;
System.Web.UI.WebControls.TextBox txt = new System.Web.UI.WebControls.TextBox();
txt = (System.Web.UI.WebControls.TextBox)e.Item.Cells[4].Controls[0];
int num = Convert.ToInt32(txt.Text.ToString());
SqlCommand cmd = new SqlCommand("sp_deletedata", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@num", SqlDbType.Int).Value = num;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
datagrid.EditItemIndex = -1;
show();
}
}

No comments: