| 1 comments ]

Repeater control is one of the light weight control when compared to the other databound controls. It provides more flexibility on the layout of data displayed and the control itself will not render any additional HTML like GridView and DataList control do. It only renders the HTML we specified in the template columns which makes it light weight when compared to other controls.

Repeater control as such will not provide edit/update functionalities for the data.

In this article, we will overcome this difficulty and provide an edit update feature similar to GridView control using the powerful jQuery library and Ajax.
Refer the below figure to understand better.







Steps
  • Open Visual Studio 2008, Click File >Website and choose ASP.Net Website.
  • Select a language of your choice. I have selected C#. You can name your website as per your need.
  • Drag a Repeater control from the data tab of the Visual Studio.
  • You can add a Sql server Express database in App_Data Folder and create a table called Employee with all the necessary fields. Enter some sample data to display in the Repeater control.
  • Specify the HeaderTemplate, ItemTemplate and FooterTemplate to display the employee data in tabular format. Bind the Repeater control from codebehind by fetching employee detail from the express database we have created in App_Data folder.
Refer the below code,
ASPX
<asp:Repeater ID="rpEmployee" runat="server">
    <HeaderTemplate>
    <table border="0" ID="tblEmployee">
        <tr id="Tr2" runat="server" style="">
            <th id="Th1">
            </th>
            <th id="Th2">
            EmpID</th>
            <th id="Th3">
            EmpName</th>
            <th id="Th4">
            Department</th>
            <th id="Th5">
            Age</th>
            <th id="Th6">
            Address</th>
       </tr>                   
    </HeaderTemplate>
    <ItemTemplate>
      <tr ID='<%# Eval("EmpID") %>'>
                    <td>                       
                        <input type="button" value="Edit"/>
                        <input type="button" value="Update" style="display:none" />
                        <input type="button" value="Cancel" style="display:none" />
                    </td>
                    <td>
                       <%# Eval("EmpID") %>
                    </td>
                    <td>
                        <%# Eval("EmpName") %>
                    </td>
                    <td>
                        <%# Eval("Department") %>
                    </td>
                    <td>
                        <%# Eval("Age") %>
                    </td>
                    <td>
                      <%# Eval("Address") %>
                    </td>
       </tr>   
    </ItemTemplate>
    <FooterTemplate>
    </table>
    </FooterTemplate>
    </asp:Repeater>

CodeBehind
protected void Page_Load(object sender, EventArgs e)
    {
            rpEmployee.DataSource = GetEmployee("Select * from Employee");
            rpEmployee.DataBind();
    }
    public DataTable GetEmployee(string query)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);
        SqlDataAdapter ada = new SqlDataAdapter(query, con);
        DataTable dtEmp = new DataTable();
        ada.Fill(dtEmp);
        return dtEmp;
    }
Execute the page and you can see the employee details in tabular view with an edit button.

Next, we will make the Repeater control’s row editable similar to the inbuilt edit feature of GridView control using jQuery library.

Providing Edit Update Feature

When the user clicks the edit button, we will hide the edit button and enable update & cancel button for that row. Just like GridView control, we will also populate the table cell value of the editing row in a textbox control to edit. After editing the value and on clicking Update button, we call a page method called UpdateEmployee() to update the employee details in the database using the jQuery’s ajax() method.

First, we will develop our page method UpdateEmployee() in our codebehind to update the employee details that is passed to it from jQuery’s ajax method.

[WebMethod]
   public static string UpdateEmployee(string empid,string name,string dept,string age,string address)  
    { 
        string UpdateQuery = "UPDATE [Employee] SET [EmpName] = @name, [Department] =  @dept, [Age] = @age, [Address] = @address WHERE [EmpID] = @empid";
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);
        con.Open();
        SqlCommand com = new SqlCommand(UpdateQuery, con);
        com.Parameters.Add("@name", SqlDbType.VarChar, 50).Value = name;
        com.Parameters.Add("@dept", SqlDbType.VarChar, 50).Value = dept;
        com.Parameters.Add("@age", SqlDbType.Int, 4).Value = age;
        com.Parameters.Add("@address", SqlDbType.VarChar, 50).Value = address;
        com.Parameters.Add("@empid", SqlDbType.Int, 4).Value = empid;       
        int n = com.ExecuteNonQuery();
        con.Close();
 
        return n.ToString();
    }


As we all know, a page method should be public static and should be decorated with WebMethod attribute. You need to include the System.Web.Services namespace for the WebMethod attribute to work. To know more about page methods and consuming it from jQuery, please read Using JQuery in ASP.Net AJAX Applications – Part 1.

Next, we will move to the client side part of our implementation where we can provide an editing option to the user. Refer the above FAQ’s to integrate jQuery library into our project.

The following jQuery code will help us to do the rest of our operations.

<script src="_scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script language="javascript">
        $(function() {
            $("#tblEmployee > tbody > tr ").each(function() {
                var TRID = $(this).attr("id");
                $(this).find("td:first > input[value=Edit]").click(function() {                   
                    ResetOtherRowEdit();
                    ChangeTableCellToTextbox(TRID);
                    $(this).hide();
                    return false;
                });
 
                $(this).find("td:first > input[value=Update]").click(function() {
                    UpdateRow(TRID);
                });
 
                $(this).find("td:first > input[value=Cancel]").click(function() {
                    CancelEdit(TRID);
                });
 
            });
        });
 
        function ChangeTableCellToTextbox(RowID) {
            $("#" + RowID + "> TD").filter(function() {
                if ($(this).find("INPUT").html() == null & !($(this).is(":nth-child(2)"))) {
                    return true;
                }
            }).each(function() {
                var TDvalue = $(this).html();               
                var replacevalue = "<input type=text value=\"" + TDvalue + "\"></input>";
                $(this).html(replacevalue);
            });
 
            $("#tblEmployee > tbody > tr[id="+ RowID +"] > td:first> input[value=Update]").show();
            $("#tblEmployee > tbody >  tr[id=" + RowID + "] > td:first> input[value=Cancel]").show();
        }
 
        function UpdateRow(RowID) {           
            var empid = $("#" + RowID + "> TD:nth-child(2)").html();
            var empname =$("#" + RowID + "> TD:nth-child(3) > input[type=text]").val();
            var dept = $("#" + RowID + "> TD:nth-child(4) > input[type=text]").val();
            var age = $("#" + RowID + "> TD:nth-child(5) > input[type=text]").val();
            var address =$("#" + RowID + "> TD:nth-child(6) > input[type=text]").val();
 
            var options = {
                type: "POST",
                url: "RepeaterEdit.aspx/UpdateEmployee",
                data: "{\"empid\":\"" + empid + "\",\"name\":\"" + empname + "\",\"dept\":\"" + dept + "\",\"age\":\"" + age + "\",\"address\":\"" + address + "\"}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(response) {
                    if (response.d != "") {
                        if (response.d == "1") {
                            alert("Updation Successful");
                            CancelEdit(RowID);
                        }
                        else {
                            alert("Updation failed!");
                        }
                    }
                }
            };
            //Call the PageMethods
            $.ajax(options);         
        }
 
        function CancelEdit(RowID) {
            $("#" + RowID + "> TD").filter(function() {
                if ($(this).find("INPUT[type=text]").val() != null) {
                    return true;
                }
            }).each(function() {              
                $(this).html($(this).find("INPUT[type=text]").val());
            });
          $("#tblEmployee > tbody > tr[id=" + RowID + "] > td:first> input[value=Update]").hide();
          $("#tblEmployee > tbody >  tr[id=" + RowID + "] > td:first> input[value=Cancel]").hide();
          $("#tblEmployee > tbody >  tr[id=" + RowID + "] > td:first> input[value=Edit]").show();
      }
 
      function ResetOtherRowEdit() {
          $("#tblEmployee > tbody > tr ").each(function() {
              var TRID = $(this).attr("id");
              if ($(this).find("td:first > input[value=Update]").css("display") == "inline") {
                  CancelEdit(TRID);
              }
          });
      }       
    </script>

Execute the page and see it in action.

The ajax() method uses JSON and POST method to send the employee data to the page method. Once the data is updated successful, the page method will return 1 which indicates success(No of rows affected in ExecuteNonQuery() in our case). On success, you will see a success alert message.

Things to consider

  • The above jQuery code will call the page method even if you have not changed the details in any cell. You can modify UpdateRow() method to call the page method only if the value is changed by comparing with initial table cell value.
  • The above jQuery code will change the table cell to textbox by populating its value to textbox directly. You can get the employee detail for that row using the employeeid from the server to get the latest data. You can write one more page method that can return the employee detail in JSON format and populate the textboxes.

1 comments

winnieqinjiaxin said... @ February 27, 2012 at 6:37 PM

Once again great post. You seem to have a good understanding of these themes.When I entering your blog,I felt this . Come on and keep writting your blog will be more attractive. To Your Success!
Classic Dresses
Classic Bridesmaid Dresses
trumpet wedding dresses
New Style Flower Girl Dresses
Wedding Dresses with Sleeves

Post a Comment