Monday, May 19, 2008

Adding records to Gridview

This is an simple application for adding new records on the form and once the record added into GridView,it will show up with newly added record with out regenerating. :-)

Here I used delete option as discard as it wants to my specific requirement.
If possible,I put AJAX version of this same module soon.



protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection con;


Cache["code"]=TextBox1.Text;
Cache["Name"]=TextBox2.Text;
Cache["DOB"]=TextBox3.Text;


con = new SqlConnection("Data Source=(local);Initial catalog=Test;user id=sa;pwd=murugesan");
con.Open();
SqlCommand smd = new SqlCommand("INSERT INTO Employee(EmpCode,Name,DOB) Values('" + Cache["code"].ToString() + "','" + Cache["Name"].ToString() + "','" + Cache["DOB"].ToString() + "')", con);

try
{

int a = (int)smd.ExecuteScalar();


}
catch (Exception ex)
{
Response.Write("Already exist !");


}


GridShow();

smd.Dispose();
con.Close();

}
public void GridShow()
{


DataSet ds = new DataSet();
con = new SqlConnection("Data Source=(local);Initial catalog=Test;user id=sa;pwd=murugesan");
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "SELECT *from Employee";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
ada = new SqlDataAdapter();
ada.SelectCommand = cmd;

ada.Fill(ds, "Employee");
GridView1.DataSource = ds;
GridView1.DataBind();
ada.Dispose();
cmd.Dispose();
con.Dispose();


}
public void Murugesan(object sender, GridViewCommandEventArgs er)
{
SqlConnection con;
SqlCommand cmd;


if (er.CommandName == "Discard")
{
string na = Convert.ToString(er.CommandArgument);
con = new SqlConnection("Data Source=(local);Initial catalog=Test;user id=sa;pwd=murugesan");
con.Open();
cmd = new SqlCommand("Delete from Employee where Name='" + na + "'", con);
cmd.ExecuteNonQuery();

GridShow();



}
}