Event Handling in Repeater Control

By Anoop S

When controls are placed in Repeater Control we have to write OnItemCommand () Event for RepeaterControl and determine which control has raised the events. Events are bubbled between the controls that is if as button is placed in Repeater and the Repeater has OnItemCommand () Event and also the button has Click Event then both the events will be fired and so it is always safe to write events only for Top-Level Controls

For example
The following source code show assign properties of RepeaterControl and handle OnItemCommand () Event for RepeaterControl.


<%@Page Language ="C#" Debug ="true"%>
<html>
<head>
<script runat ="server">

protected void Page_Load(object sender, EventArgs e)
{

ArrayList
al = new ArrayList();
for (int i =1; i<10; i++)
{
al.
Add(new AddressBook ("Name#" + i.ToString(), "mail@mail " + i.ToString()));
Repeater
.DataSource = al;
Repeater
.DataBind();
}
}

protected void Repeater_Action(object sender, RepeaterCommandEventArgs re)
{
label1.
Text =" You Selected " + ((LinkButton)re.CommandSource).Text;
}
public class AddressBook
{
private string _Name;
private string _Email;  
public  AddressBook( string name, string email)
{
this._Name = name;
this._Email =email;
}

public string Name
{
get
{
return this._Name;
}
}

public string Email
{
get
{
return this._Email;
}
}
}

</script>
</head>
<body>
<form id="Form1" runat="server">
<h1><asp:Label id="label1"  runat="server"/> </h1>
<asp:Repeater runat="server" id="Repeater" OnItemCommand="Repeater_Action">
<HeaderTemplate>
<table border=1 cellspacing="0" cellpadding ="0" width=100%>
<tr bgcolor="teal" >
<td>Name</td>
<td>eMail</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr bgcolor="aqua" >
<td><asp:LinkButton ID="LinkButton1" runat ="server" Text=<%#DataBinder.Eval(Container.DataItem,"Name") %>/></td>
<td><b><%#DataBinder.Eval(Container.DataItem,"Email")%>/></b></td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr bgcolor="lime">
<td><%#DataBinder.Eval(Container.DataItem,"Name")%>/></td>
<td><asp:LinkButton ID="LinkButton2" runat="server" Text =<%#DataBinder.Eval(Container.DataItem,"Email")%>/></td>
</tr>
</AlternatingItemTemplate>
<FooterTemplate>
</Table>
</FooterTemplate>
</asp:Repeater>
</form>
</body>
</html>

Event Handling in Repeater Control  (2137 Views)