Gridview Edit,Delete,Insert and Update in ASP .NET 4.5

This article is about Gridview,How to use Gridview?Here you will get know about use of Gridview Events i.e RowEditing,RowEditing,RowUpdating,RowDeleting,RowCommand, RowDataBound and RowCancelingEdit.For this I will perform Insert,Edit,Delete and Update on gridview. Gridview is ASP .NET control used to display data in tabular format. Gridview is widely used controls and very important control in Web Application. To perform various operations create database tables:Students and Department.
Student

student_id | name | roll_no | department_id | status

Department

department_id | name
Now in aspx page add gridview control and edit it as follow:
<asp:GridView ID="grdStudent" runat="server"
OnRowCancelingEdit="grdStudent_RowCancelingEdit"
OnRowCommand="grdStudent_RowCommand"
OnRowEditing="grdStudent_RowEditing"
OnRowUpdating="grdStudent_RowUpdating"
OnRowDeleting="grdStudent_RowDeleting"
OnRowDataBound="grdStudent_RowDataBound"
ShowFooter="True" DataKeyNames="student_id,department,status" 
AutoGenerateColumns="False"
EmptyDataText="No Records."
></asp:GridView>
Add columns to gridview,for each column add <asp:TemplateField >. This field will contain an ItemTemplate to bound data,EditTemplate for update controls and FooterTemplate for input controls.Also add CommandField for insert,edit,update and delete links.
<asp:TemplateField HeaderText="Department">
<ItemTemplate>
<asp:Label ID="lblDepartment" runat="server" Text='<%# Bind("department") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlDepartment" runat="server">
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlNewDepartment" runat="server">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
Let's go for server-side C# code
  1. Fill GridView: To fill GridView write method bindGrid, which will set Grid DataSource to DataSet containing Student data and then bind.Initially there will be no data to bind in this case show one row containing Input controls for respective columns of GridView, which is achieved by adding NewRow to empty DataSet.
    private void bindGrid()
     {
       DataSet ds = student.getAllStudent();
       if (ds.Tables[0].Rows.Count > 0)
       {
         grdStudent.DataSource = ds;
         grdStudent.DataBind();
       }
       else
       {
         ds.Tables[0].Rows.Add( ds.Tables[0].NewRow() );
        grdStudent.DataSource = ds;
        grdStudent.DataBind();
        grdStudent.Rows[0].Cells.Clear();
       }
     }
  2. For Insert or Edit data, we must fill the DropDownList Dynamically at the time of Data Binding. For this use RowDataBound event of GridView.
    protected void grdStudent_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
    
                    DropDownList ddlStatus = (DropDownList)e.Row.FindControl("ddlStatus");
                    if (ddlStatus != null)
                    {
                        ddlStatus.SelectedValue = ddlStatus.Items.FindByText(grdStudent.DataKeys[e.Row.RowIndex].Values[2].ToString()).Value;
                    }
                    DropDownList ddlDepartment = (DropDownList)e.Row.FindControl("ddlDepartment");
                    if (ddlDepartment!=null)
                    {
                        ddlDepartment.DataSource = department.getAllDepartment();
                        ddlDepartment.DataValueField = "department_id";
                        ddlDepartment.DataTextField = "name";
                        ddlDepartment.DataBind();
                        ddlDepartment.SelectedValue = ddlDepartment.Items.FindByText(grdStudent.DataKeys[e.Row.RowIndex].Values[1].ToString()).Value;
                    }
                }
                if (e.Row.RowType==DataControlRowType.Footer)
                {
                    DropDownList ddlNewDepartment = (DropDownList)e.Row.FindControl("ddlNewDepartment");
                    ddlNewDepartment.DataSource = department.getAllDepartment();
                    ddlNewDepartment.DataValueField = "department_id";
                    ddlNewDepartment.DataTextField = "name";
                    ddlNewDepartment.DataBind();
                }
               
            }
     
  3. Add New Data:To Insert New Student I have added Link for Insert with CommandArgument="Insert". Whenever GridView is filled the footer row containing dropdownlist will be filled dynamically. After clicking "Insert" the RowCommand event of GridView is called where insertion takes place.
     protected void grdStudent_RowCommand(object sender, GridViewCommandEventArgs e)
            {
                if (e.CommandName.Equals("Insert"))
                {
                    TextBox txtNewName = (TextBox)grdStudent.FooterRow.FindControl("txtNewName");
                    TextBox txtNewRollNo = (TextBox)grdStudent.FooterRow.FindControl("txtNewRollNo");
                    DropDownList ddlNewDepartment = (DropDownList)grdStudent.FooterRow.FindControl("ddlNewDepartment");
                    DropDownList ddlNewStatus = (DropDownList)grdStudent.FooterRow.FindControl("ddlNewStatus");
                   
                    student.name = txtNewName.Text;
                    student.roll_no = Convert.ToInt32(txtNewRollNo.Text);
                    student.department_id = Convert.ToInt32(ddlNewDepartment.SelectedValue);
                    student.status = Convert.ToInt32(ddlNewStatus.SelectedValue);
                    student.insertStudent(student);
                    bindGrid();
                    
                }
            }
     
  4. Update student: For updating student user have to click "Edit" Command which executes RowEditing event where we must set EditIndex of GridView which enables the Edit controls of the selected row.After Editing for updation RowUpdating event is called after clicking "Update" Command OR RowCancellingEdit event is called in case "Cancel" is clicked.
     protected void grdStudent_RowEditing(object sender, GridViewEditEventArgs e)
            {
                grdStudent.EditIndex = e.NewEditIndex;
                bindGrid();
            }
    
            protected void grdStudent_RowUpdating(object sender, GridViewUpdateEventArgs e)
            {
                Label lblId = (Label)grdStudent.Rows[e.RowIndex].FindControl("lblStudentId");
                TextBox txtName = (TextBox)grdStudent.Rows[e.RowIndex].FindControl("txtName");
                TextBox txtRollNo = (TextBox)grdStudent.Rows[e.RowIndex].FindControl("txtRollNo");
                DropDownList ddlDepartment = (DropDownList)grdStudent.Rows[e.RowIndex].FindControl("ddlDepartment");
                DropDownList ddlStatus = (DropDownList)grdStudent.Rows[e.RowIndex].FindControl("ddlStatus");
                student.student_id = Convert.ToInt32(lblId.Text);
                student.name = txtName.Text;
                student.roll_no = Convert.ToInt32(txtRollNo.Text);
                student.department_id = Convert.ToInt32(ddlDepartment.SelectedValue);
                student.status = Convert.ToInt32(ddlStatus.SelectedValue);
                student.updateStudent(student);
                grdStudent.EditIndex = -1;
                bindGrid();
            }
            protected void grdStudent_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
            {
                grdStudent.EditIndex = -1;
                bindGrid();
            }

  5. Delete student: For deletion I have added "Delete" Command,which will call RowDeleting event of GridView.
     protected void grdStudent_RowDeleting(object sender, GridViewDeleteEventArgs e)
            {
                Label lblId = (Label)grdStudent.Rows[e.RowIndex].FindControl("lblStudentId");
                student.deleteStudent(Convert.ToInt32(lblId.Text));
                bindGrid();
            }
     
NOTE: After each operation which modifies the data we must refresh the GridView. So,here you have editable GridView,you can now Insert,Edit,Update and Delete data in GridView,rather than using forms.You can always use this method for Data operations in GridView except when the number of tables or number of columns are too high or when complexity increases.

Comments