To connect to database :
protected void Page_Load(object sender, EventArgs e)
{
string constr = "server=servername;database=databasename;integrated security=sspi";
con = new SqlConnection(constr);
da = new SqlDataAdapter("select * from employee", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
To Edit into GridView :
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
t1 = new TextBox();
t2 = new TextBox();
t1.Text = GridView1.Rows[e.NewEditIndex].Cells[0].Text;
t2.Text = GridView1.Rows[e.NewEditIndex].Cells[1].Text;
GridView1.DataBind();
}
To cancel the Gridview changes:
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
GridView1.DataBind();
}
To delete a row in Gridview :
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//da = new SqlDataAdapter("delete * from employee where empid =" + e.RowIndex ,con);
string str = GridView1.Rows[e.RowIndex].Cells[0].Text;
int delVal = Convert.ToInt32(str);
con.Open();
SqlCommand cmd = new SqlCommand("delete from employee where empid = "+ delVal , con);
cmd.ExecuteNonQuery();
con.Close();
GridView1.DataBind();
}
To Update the Gridview :
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
if (row != null)
{
TextBox t = new TextBox();
t = (TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0];
if (t != null)
{
con.Open();
string str1 = "Update employee set empname = '" + t.Text + "' where empid = 59";
SqlCommand cmd = new SqlCommand( str1 , con);
cmd.ExecuteNonQuery();
con.Close();
GridView1.DataBind();
}
}
}
Monday, 17 September 2007
Subscribe to:
Posts (Atom)