CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
GridView Style Edit Update in Repeater Control Using jQuery and Ajax

By Satheesh Babu
Posted On Jun 26,2009
Article Rating:
Average Rating: 5
No of Ratings: 2
No of Comments: 6
Category: jQuery/ASP.Net
Print this article.

GridView Style Edit Update in Repeater Control Using jQuery and Ajax

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. Read my article Choosing the Right DataBound Controls in ASP.Net to know more.

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.

 

Edit Update Feature in ASP.Net Repeater Control

 

Steps

1.      Open Visual Studio 2008 IDE.

2.      Using a language of your choice, create a new website with appropriate name.

3.      Drag a Repeater control from the data tab of the Visual Studio.

4.      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.

5.      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;

    }

 

Web.Config

<connectionStrings>

  <add name="DatabaseConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"

   providerName="System.Data.SqlClient" />

 </connectionStrings>

 

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

If you are not familiar with jQuery library, I encourage you to read the following FAQ’s to have a basic understanding on the library.

What is jQuery? How to use it in ASP.Net Pages?

How to enable jQuery intellisense in Visual Studio 2008?

How to use jQuery intellisense in an external javascript file?

 

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 2.

 

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.

 

Download the source attached with this article in Download section and see it in action.

 

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.

 

Downloads

Download Source 

 

Conclusion

Repeater control is considered as a read only control and it is used only in scenarios where it requires only display of data. Wherever there is a need to edit the data, developers always preferred GridView and DataList control. With the release of jQuery library, it is now possible to provide an easy edit update feature for Repeater control. Download the source attached with this article and see it in action.

Happy coding!!

 

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Very Nice
It is very helpful for beginner
Nice!
Just what I needed, thanks for the clear write up.
Create new row?
I'm new to JQuery and am trying to figure out how to add a new row and insert the table. Great article BTW! Thanks.
Nice Artical
Its really A Nice Artical That Describe So perfectly..Its really A helpful Artical to the new Users...I Like This....
RE:Problem Attaching Functions to Buttons
Even though, you have not written TBODY the browser will automatically insert it. Please read the following discussions to know more,
http://www.codingforums.com/archive/index.php/t-142587.html

The above code is tested in IE 7.0 and FF 3.X.
Problem Attaching Functions to Buttons
Many thanks for the article. I tried to run this, but the click event is not getting attached to the "Edit" button in the ready function.

My HTML is a little weak, but when I look at the page source, I do not see a "TBODY" tag in the page. It certainly is not in the aspx file. When I remove the tbody tag from the line '#tblEmployee > tbody > tr ', the click event still does not get attached. I see the tbody tag used throughout the javascript, but nowhere in the page source.

Is this an error in the code, or am I missing something.

Many thanks
Mike Thomas