Tuesday, December 27, 2011

GridView Edit , Update and Delete


GridView-

 
GridView is one of the controls of type, Data Control in ASP.Net, which is used for data representation on web page. GridView not only is used for showing data but also we can perform operation like- Edit, Update, Cancel  and Delete using GridView.
 

GridView has some in-built events, using these events you can perform these operations. For this you have to implement following events of GridView-

1.     GrdEmpData_RowEditing
2.     GrdEmpData_RowDeleting
3.     GrdEmpData_RowUpdating
4.     GrdEmpData_RowCancelingEdit

By implementing these events, you can perform Edit, Delete and Update operations in GridView.

In this article I am going to explain, How you can perform these operations in GridView? 

First design GridView like this-

.aspx code-

 
 <asp:GridView ID="GrdEmpData" runat="server" AutoGenerateColumns="false"
               Width ="50%" onrowcancelingedit="GrdEmpData_RowCancelingEdit"
             onrowdeleting="GrdEmpData_RowDeleting" onrowediting="GrdEmpData_RowEditing"
             onrowupdating="GrdEmpData_RowUpdating" >
                <Columns>
                    <asp:TemplateField HeaderText="EmpId" ItemStyle-HorizontalAlign  ="Left"  ItemStyle-Width ="10%">
                        <ItemTemplate>
                            <asp:Label ID="lblEmpId" runat="server" Text='<% # Eval("EmpId") %>'></asp:Label>
                        </ItemTemplate>
                     </asp:TemplateField>
                    <asp:TemplateField HeaderText="EmpName" ItemStyle-HorizontalAlign  ="Left"  ItemStyle-Width ="40%">
                        <ItemTemplate>
                            <asp:Label ID="lblEmpName" runat="server" Text='<% # Eval("EmpName") %>'></asp:Label>
                        </ItemTemplate>
                         <EditItemTemplate >
                            <asp:TextBox ID="TxtEmpName" runat="server" Text='<% # Eval("EmpName") %>'></asp:TextBox>
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Salary" ItemStyle-HorizontalAlign  ="Left"  ItemStyle-Width ="20%">
                        <ItemTemplate>
                            <asp:Label ID="lblSalary" runat="server" Text='<% # Eval("Salary") %>'></asp:Label>
                        </ItemTemplate>
                        <EditItemTemplate >
                            <asp:TextBox ID="TxtSalary" runat="server" Text='<% # Eval("Salary") %>'></asp:TextBox>
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:CommandField ShowEditButton ="true"  HeaderText ="Edit" ItemStyle-Width ="20%"/>
                    <asp:TemplateField  HeaderText="Delete" ItemStyle-HorizontalAlign  ="Left"  ItemStyle-Width ="10%">
                        <ItemTemplate>
                            <asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" CommandName ="delete"   CommandArgument='<% # Eval("EmpId") %>' OnClientClick ="return confirm('Do you want to delete this record?;')"></asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>



In above .aspx code, I have designed one GridView with 5 columns - EmpId, EmpName, Salary and 2 columns for Edit and Delete records.

For editing,   I have taken ComnmandField , This is built-in column for GridView by setting "ShowEditButoin= true" we can add it to GridVIew like this-

   <asp:CommandField ShowEditButton ="true"  HeaderText ="Edit" ItemStyle-Width ="20%"/>

For deleting,   I have taken LinkButton in TemplateField  because I want to show delete confirmation . Like this-

  <ItemTemplate>
      <asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" CommandName ="delete"   CommandArgument='<% # Eval("EmpId") %>' OnClientClick ="return confirm('Do you want to delete this record?;')">
       </asp:LinkButton>
   </ItemTemplate>


Here first, I am showing delete confirmation message using JavaScript.

.cs code-

To bind record to the GridView , I have written one function GetData(), After setting the record from server GridView will be bounded with fetched record in Page_Load() event. For increasing the performance, I have called GetData() function in if() condition, so that at the time of postback GridView will not be bounded again.

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                //Binding Data to GridView
                GetData();
            }
        }
        catch (Exception ex)
        {
            Response.Write(@"<script>alert('" + ex.Message + "')</script>");
        }
    }
  
    //Function to get data from database
    private void GetData()
    {
        try
        {
            DataTable dt = null;
            string conString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
            SqlConnection con = new SqlConnection(conString);
            SqlDataAdapter da = new SqlDataAdapter("select * from tab_EmpMaster", con);
            dt = new DataTable();
            da.Fill(dt);
            GrdEmpData.DataSource = dt;
            GrdEmpData.DataBind();
        }
        catch (Exception ex)
        {
            Response.Write(@"<script>alert('" + ex.Message + "')</script>");
        }
    }


To perform operation on GridView, I have created one generic function. This function will accept SQL query as input and it will execute this query using  SqlCommand object. This function is specific for DML operations like- Insert, Update and Delete.

//Function to perform DML
    private void PerformDML(string strQuery)
    {
        try
        {
            string conString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
            SqlConnection con = new SqlConnection(conString);
            con.Open();
            SqlCommand cmd = new SqlCommand(strQuery, con);
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Response.Write(@"<script>alert('" + ex.Message + "');</script>");
        }
    }


To perform operation on GridView, you have to just pass SQL query in this function. Here we need to frame query based on GridView actions. Now I am implementing GridView events to perform operations.

//Code to edit

    protected void GrdEmpData_RowEditing(object sender, GridViewEditEventArgs e)
    {
        try
        {
            GrdEmpData.EditIndex = e.NewEditIndex;
            //Rebind Grid
            GetData();
        }
        catch (Exception ex)
        {
          Response.Write(@"<script>alert('" + ex.Message + "')</script>");
        }
    }


 When you will click on edit button, then GridView will display Update and Cancel button.


//Code to cancel

    protected void GrdEmpData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        try
        {
            //Setting Grid to non editable mode
            GrdEmpData.EditIndex = -1;
            //Rebind Grid
            GetData();
        }
        catch (Exception ex)
        {
            Response.Write(@"<script>alert('" + ex.Message + "')</script>");
        }
    }


//Code to Update

    protected void GrdEmpData_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        try
        {
            Label lblEmpId = (Label)GrdEmpData.Rows[e.RowIndex].FindControl("lblEmpId");
            TextBox txtEmpName = (TextBox)GrdEmpData.Rows[e.RowIndex].FindControl("TxtEmpName");
            TextBox txtSalary = (TextBox)GrdEmpData.Rows[e.RowIndex].FindControl("TxtSalary");

            if (lblEmpId != null && txtEmpName !=null && txtSalary !=null)
            {
                int empId = Convert.ToInt32(lblEmpId.Text);
                string strQuery = "update tab_EmpMaster set empname='" + txtEmpName.Text + "', salary=" + Convert.ToDecimal(txtSalary.Text) + " where empid=" + Convert.ToInt32(lblEmpId.Text) + " ";
                PerformDML(strQuery);
                Response.Write("<script>alert('Record updated  successfully.')</script>");
                //Setting Grid to non editable mode
                GrdEmpData.EditIndex = -1;
                //Rebind Grid
                GetData();
            }

        }
        catch (Exception ex)
        {
            Response.Write(@"<script>alert('" + ex.Message + "')</script>");
        }
    }


//Code to Delete

    protected void GrdEmpData_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            Label lblEmpId = (Label)GrdEmpData.Rows[e.RowIndex].FindControl("lblEmpId");
            if (lblEmpId != null)
            {
                int empId = Convert.ToInt32(lblEmpId.Text);
                string strQuery="delete from tab_EmpMaster where empid=" + empId + " ";
                PerformDML(strQuery);
                Response.Write("<script>alert('Record deleted successfully.')</script>");
                //Rebind Grid
                GetData();
            }

        }
        catch (Exception ex)
        {
            Response.Write(@"<script>alert('" + ex.Message + "')</script>");
        }
    }


Note-  


After clicking delete button, you will get confirmation box.

In all operation, first we need to get the id for particular record to which we want to update or delete, because based on that only operation will be performed. To get Control's value from GridView I have used FindControl() method. This method returns particular object if it is found otherwise it returns null value.

By using this code you can easily perform operations on GridView.


Thanks

3 comments: