Tuesday 14 May 2013

Repeater Control


Asp.Net Using C# Repeater Control


The Repeater control is used to display a repeated list of items that are bound to the control. It enable the customization of the layout by each repeated list of items. The Repeater control may be bound to a database table, an XML file, or another list of items. The Repeater control has no built-in select and edit support.
But today i show you how to edit,update,delete and update in repeater control. Most of the developers didn't know about this, but yes it is posible.

Repeater is a data-bound container control that can be used to automate the display of a collection
of repeated list items.The Repeater control contains the following five templates:

1.Header Template
2.ItemTemplate
3.AlternatingltemTemplate
4.Separator Template
5.AlternatingltemTemplate
6.FooterTemplate
First create a default page and place repeater control in default page
then start coading in cs file(Default.aspx.cs).
In repeater we write ourself in html for binding  not like GridView just put the control in it and then bind with Eval("something").
I am displaying name and employeeID in repeater control so you can understand it easily.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="repeater.aspx.cs" Inherits="repeater" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head id = "Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:Repeater ID="Repeater1" runat="server" 
            onitemcommand="Repeater1_ItemCommand">
            <HeaderTemplate>
            <table><tr bgcolor="#FF6600"><td>Name</td><td>Address</td><td>Action</td></tr></table></HeaderTemplate>


</asp:Repeater>
    
    </div>
    </form>
</body>
</html>

I write all heading in Headertemplate like we do it in gridview, don't forget to close it.

Now write in item template to show data, just write the same i am and add more contents to show more.


<ItemTemplate><tr><td> <asp:Label ID="Label1" runat="server" Text='<%#Eval("workername") %>'></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server" Text='<%#Eval("workername") %>'Visible="false"></asp:TextBox>
        </td>
        <td>
        <asp:Label ID="Label2" runat="server" Text='<%#Eval("currentadd") %>'></asp:Label>
        <asp:TextBox ID="TextBox2" runat="server" Text='<%#Eval("currentadd") %>'Visible="false"></asp:TextBox>
        </td>
         <td>
        <asp:LinkButton ID="LinkEdit" runat="server" CommandArgument='<%#Eval("id") %>' CommandName="edit">Edit</asp:LinkButton>
            <asp:LinkButton ID="LinkDelete" runat="server" CommandArgument='<%#Eval("id") %>' CommandName="delete">Delete</asp:LinkButton>
            <asp:LinkButton ID="LinkUpdate" runat="server" CommandArgument='<%#Eval("id") %>' CommandName="update"Visible="false">Update</asp:LinkButton>
            <asp:LinkButton ID="Linkcancel" runat="server" CommandArgument='<%#Eval("id") %>' CommandName="cancel"Visible="false">Cancel</asp:LinkButton>
            </td>
        </tr>
            
       
        
        </ItemTemplate>


Now see i change visibility of some controls to false which are highlited above. If we not change it then it show record in label as well as in textbox also when we run the page. So to fix this just false the controls which are not used in first when user view. Links are also set to visible false because when we click to edit then only user see update and cancel link, else default view is Label1,label2, Linkbutton(EDIT) and linkbutton(DELETE).
You can take simple button also instead of linkbutton as your requirement.


Now come to the coading part::


First create the bind method which show the data from repeater control



public void Show_Data()
    {
        SqlDataAdapter adp = new SqlDataAdapter("select * from tbexecutive ORDER BY workername ASC", con);
        DataSet ds = new DataSet();
        adp.Fill(ds);
        Repeater1.DataSource = ds;
        Repeater1.DataBind();
    }




 and call it in page load::





protected void Page_Load(object sender, EventArgs e)
    {
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        if (Page.IsPostBack == false)
        {
            Show_Data();
        }
    }

Now the main part starts here, fire the event item command of repeater  and every coading is done in it.

As you remember we give every linkbutton Command name and bind with CommandArgument

For linkbutton edit write this code::



if (e.CommandName == "edit")
        {
            ((Label)e.Item.FindControl("Label1")).Visible = false;
            ((Label)e.Item.FindControl("Label2")).Visible = false;
            ((TextBox)e.Item.FindControl("Textbox1")).Visible = true;
            ((TextBox)e.Item.FindControl("Textbox2")).Visible = true;
            ((LinkButton)e.Item.FindControl("LinkEdit")).Visible = false;
            ((LinkButton)e.Item.FindControl("LinkDelete")).Visible = false;
            ((LinkButton)e.Item.FindControl("LinkUpdate")).Visible = true;
            ((LinkButton)e.Item.FindControl("Linkcancel")).Visible = true;
        }
Find all controls in repeater first and then set visibility False and True when Edit link is pressed, By pressing Edit linkbutton TextBox and Update and Cancel Link show so here we set their visibility true and other false and same for other links.

In Delete link button:: no view is changed just selected roe is deleted from the record and then we call the bind function to show record and message script.


if (e.CommandName == "delete")
        {
            SqlCommand cmd = new SqlCommand("delete from tbexecutive where id=@id", con);
            cmd.Parameters.AddWithValue("@id", e.CommandArgument);
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            Page.ClientScript.RegisterStartupScript(this.GetType(), "ch", "<script>alert('Data Deleted Successfully')</script>");
            Show_Data();
        }
Here id is bind with command argument, see in sourcefile.


In Update link:: first i find the TextBox where user change the data and put it in string value str1,str2.
Then i update the record with DataAdapter, you can do it with sqlcommand cmd also. Just change the adapter with sqlcommand ad then execute the nonquery.



if (e.CommandName == "update")
        {
            string str1 = ((TextBox)e.Item.FindControl("TextBox1")).Text;
            string str2 = ((TextBox)e.Item.FindControl("TextBox2")).Text;
            SqlDataAdapter adp = new SqlDataAdapter("update tbexecutive set workername=@name, currentadd=@add where id=@id", con);
            adp.SelectCommand.Parameters.AddWithValue("@name", str1);
            adp.SelectCommand.Parameters.AddWithValue("@add", str2);
            adp.SelectCommand.Parameters.AddWithValue("@id", e.CommandArgument);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            Show_Data();
            Page.ClientScript.RegisterStartupScript(this.GetType(), "ch", "<script>alert('Congratulations !! Selected Record is Updated')</script>");
        }


In cancel LinkButton:: View is changed to the default which shows label and edit and delete link. se here we set visibility false and true.



if (e.CommandName == "cancel")
        {
            ((Label)e.Item.FindControl("Label1")).Visible = true;
            ((Label)e.Item.FindControl("Label2")).Visible = true;
            ((TextBox)e.Item.FindControl("TextBox1")).Visible = false;
            ((TextBox)e.Item.FindControl("TextBox2")).Visible = false;
            ((LinkButton)e.Item.FindControl("LinkEdit")).Visible = true;
            ((LinkButton)e.Item.FindControl("LinkDelete")).Visible = true;
            ((LinkButton)e.Item.FindControl("LinkUpdate")).Visible = false;
            ((LinkButton)e.Item.FindControl("Linkcancel")).Visible = false;
        }


After doing all coading and binding repeater show like this, Do it like a example and use it in your your project.
 Here now I am showing you all the coading and source file so you can use it easily::



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="repeater.aspx.cs" Inherits="repeater" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id = "Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:Repeater ID="Repeater1" runat="server" 
            onitemcommand="Repeater1_ItemCommand">
            <HeaderTemplate>
            
            <table width="350"><tr bgcolor="#FF6600"><td>Name</td><td>Address</td><td>Action</td></tr></HeaderTemplate>
             <ItemTemplate><tr><td> <asp:Label ID="Label1" runat="server" Text='<%#Eval("workername") %>'></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server" Text='<%#Eval("workername") %>' Visible="false"></asp:TextBox>
        </td>
        <td>
        <asp:Label ID="Label2" runat="server" Text='<%#Eval("currentadd") %>'></asp:Label>
        <asp:TextBox ID="TextBox2" runat="server" Text='<%#Eval("currentadd") %>' Visible="false"></asp:TextBox>
        </td>
         <td>
        <asp:LinkButton ID="LinkEdit" runat="server" CommandArgument='<%#Eval("id") %>' CommandName="edit">Edit</asp:LinkButton>
            <asp:LinkButton ID="LinkDelete" runat="server" CommandArgument='<%#Eval("id") %>' CommandName="delete">Delete</asp:LinkButton>
            <asp:LinkButton ID="LinkUpdate" runat="server" CommandArgument='<%#Eval("id") %>' CommandName="update" Visible="false">Update</asp:LinkButton>
            <asp:LinkButton ID="Linkcancel" runat="server" CommandArgument='<%#Eval("id") %>' CommandName="cancel" Visible="false">Cancel</asp:LinkButton>
            </td>
        </tr>
            
       
        
        </ItemTemplate>
        </asp:Repeater>
    
    </div>
    </form>
</body>
</html>


CS.FILE  code is here:: 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;

public partial class repeater : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        if (Page.IsPostBack == false)
        {
            Show_Data();
        }
    }
    protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "edit")
        {
            ((Label)e.Item.FindControl("Label1")).Visible = false;
            ((Label)e.Item.FindControl("Label2")).Visible = false;
            ((TextBox)e.Item.FindControl("Textbox1")).Visible = true;
            ((TextBox)e.Item.FindControl("Textbox2")).Visible = true;
            ((LinkButton)e.Item.FindControl("LinkEdit")).Visible = false;
            ((LinkButton)e.Item.FindControl("LinkDelete")).Visible = false;
            ((LinkButton)e.Item.FindControl("LinkUpdate")).Visible = true;
            ((LinkButton)e.Item.FindControl("Linkcancel")).Visible = true;
        } if (e.CommandName == "delete")
        {
            SqlCommand cmd = new SqlCommand("delete from tbexecutive where id=@id", con);
            cmd.Parameters.AddWithValue("@id", e.CommandArgument);
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            Page.ClientScript.RegisterStartupScript(this.GetType(), "ch", "<script>alert('Data Deleted Successfully')</script>");
            Show_Data();
        }
        if (e.CommandName == "update")
        {
            string str1 = ((TextBox)e.Item.FindControl("TextBox1")).Text;
            string str2 = ((TextBox)e.Item.FindControl("TextBox2")).Text;
            SqlDataAdapter adp = new SqlDataAdapter("update tbexecutive set workername=@workername, currentadd=@add where id=@id", con);
            adp.SelectCommand.Parameters.AddWithValue("@workername", str1);
            adp.SelectCommand.Parameters.AddWithValue("@add", str2);
            adp.SelectCommand.Parameters.AddWithValue("@id", e.CommandArgument);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            Show_Data();
            Page.ClientScript.RegisterStartupScript(this.GetType(), "ch", "<script>alert('Congratulations !! Selected Record is Updated')</script>");
        } if (e.CommandName == "cancel")
        {
            ((Label)e.Item.FindControl("Label1")).Visible = true;
            ((Label)e.Item.FindControl("Label2")).Visible = true;
            ((TextBox)e.Item.FindControl("TextBox1")).Visible = false;
            ((TextBox)e.Item.FindControl("TextBox2")).Visible = false;
            ((LinkButton)e.Item.FindControl("LinkEdit")).Visible = true;
            ((LinkButton)e.Item.FindControl("LinkDelete")).Visible = true;
            ((LinkButton)e.Item.FindControl("LinkUpdate")).Visible = false;
            ((LinkButton)e.Item.FindControl("Linkcancel")).Visible = false;
        }

    }
    public void Show_Data()
    {
        SqlDataAdapter adp = new SqlDataAdapter("select * from tbexecutive ORDER BY workername ASC", con);
        DataSet ds = new DataSet();
        adp.Fill(ds);
        Repeater1.DataSource = ds;
        Repeater1.DataBind();
    }
}

No comments:

Post a Comment