Wednesday, February 9, 2011

How to edit,update,delete and cancel in gridview using Aspnet

Hi friends.. In this article i would like to explain how to apply CRUD(Create,Edit,Delete,Update)
Operations for GridView.Where this Operations will be held inside the gridview(this is one method)
we have another method also (Click here to know the procedure).So Lets the Procedure


First,Open the visual studio 2008

Next,select one aspnet web application and click ok

Next,open the Design page of Default.aspx

Next,Drag and Drop one grid view from ToolBox

Next,Right click on the gridview and select properties.

In the properties window,double click on the following events

RowCancelingEdit

RowEditing

RowUpdating

Next,come to the Code page that is,Default.aspx.cs and write copy the following code

In the page load,Bind the grid view


protected void Page_Load(object sender, EventArgs e)
    {
       try
        {
          SqlConnection  con = new SqlConnection(ConfigurationManager.ConnectionStrings["Testing"].ToString());
           
            if (!Page.IsPostBack)
            {               
                GetData();                
            }            
        }
        catch (Exception ex)
        {
            lblstatus.Text=ex.message;
        }
   }
   

Next,Create a method GetData()

private void GetData()
    {
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }           
            SqlCommand com = new SqlCommand("select * from Testing ", con);
            SqlDataAdapter da = new SqlDataAdapter(com);
            DataSet ds = new DataSet();
            da.Fill(ds, "Testing");
            GvTesting.DataSource = ds;
            GvTesting.DataBind();

        }
        catch (Exception ex)
        {
            lblstatus.Text = ex.Message;
        } 
   }
   
   

For Editing Procedure,write the following code

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

    {

        GridView1.EditIndex = e.NewEditIndex;

        GridView1.DataSource = GetData();

        GridView1.DataBind();

    }


For Updating the Grid,write the following code

Updating Procedure

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

string empid = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].FindControl("txt_empid")).Text;

string empname =((TextBox)GridView1.Rows[e.RowIndex].Cells[2].FindControl("txt_empname")).Text;

string desgination = ((DropDownList)GridView1.Rows[e.RowIndex].Cells[3].FindControl("gvddlDesignation")).SelectedItem.ToString();      
   

string company = ((TextBox)GridView1.Rows[e.RowIndex].Cells[6].FindControl("txt_cname")).Text;
     

        GridView1.EditIndex = -1;

        GridView1.DataSource = GetData();

        GridView1.DataBind();

        Response.Write("Update Seccessful!");                                                                          

    }


Create Update Record Method to update data in database

private void UpdateRecord(string empid,string desgination,string empname, string company)

    {
string sqlStatement = "UPDATE Employee_Details " +"SET EmpName = @EmpName,Desgination=@Desgination,CompanyName = @CompanyName " + "WHERE EmpID = @EmpID";

        try

        {

            con = new SqlConnection(ConfigurationManager.ConnectionStrings["SAMPLE_2"].ToString());

            con.Open();

            SqlCommand cmd = new SqlCommand(sqlStatement, con);

            cmd.Parameters.AddWithValue("@EmpName", empname);

            cmd.Parameters.AddWithValue("@Desgination", desgination);

            cmd.Parameters.AddWithValue("@CompanyName", company);

            cmd.Parameters.AddWithValue("@EmpID", empid);

            cmd.CommandType = CommandType.Text;

            cmd.ExecuteNonQuery();

        }

        catch (System.Data.SqlClient.SqlException ex)

        {

            string msg = "Insert/Update Error:";

            msg += ex.Message;

            throw new Exception(msg);

        }

        finally

        {

            con.Close();

        }

    }



For Cancel

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

    {

        GridView1.EditIndex = -1;

        GridView1.DataSource = GetData();

        GridView1.DataBind();

    }


For Deletion Operation

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
            SqlCommand cmdDelete = new SqlCommand();
            cmdDelete.CommandText = "Delete Testing where TestingId=" + int.Parse(id);
            cmdDelete.Connection = con;
            if (con.State == ConnectionState.Closed)
                con.Open();
            cmdDelete.ExecuteNonQuery();
            con.Close();
            GetData();
            lblstatus.Text = "Record Successfully Deleted";
            lblstatus.ForeColor = Color.Red;
        }
        catch (Exception ex)
        {
            lblstatus.Text = "Falied to Delete Record";
            lblstatus.ForeColor = Color.Red;
        }
    }
    
    

That's it....Happy Coding.....:)

developercode
About the Author
Sayyad is a Software Engineer, Blogger and Founder of Developers Code from India.His articles mainly focus on .Net (Web and Windows based applications), Mobile Technologies (Android,IPhone,BlackBerry) and SEO.

Labels: , , , ,