Here is the deal,
I got a list of documents which is generated by the repeater and his databinding. In my markup i got a class for "li" tag when active or not.
What i just need is to set class="active" on the Li parent tag of my linkbutton when the document is selected.
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:LinkButton ID="lnk" runat="server" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "Id") %>' OnCommand="Get_carte"><%# Container.FindControl("lnk").ClientID %> <%# DataBinder.Eval(Container.DataItem, "Name") %> - <%# DataBinder.Eval(Container.DataItem, "id") %> - <%# DataBinder.Eval(Container.DataItem, "compteur") %></asp:LinkButton></li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
I've finally found a solution for my issue.
#Kapil : Your code works but got issue with the reload of the aspx page, then i can't use this method.
#Aghilas : I based my solution on your code.
In fact i can't use ItemDataBound event because i bind only 1 time my repeater, then i use my OnCommand event on the linkbutton. Here is my aspx code:
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Rpt_DataBound">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li runat="server" ID="li">
<asp:LinkButton ID="lnk" class="linkButton" runat="server" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "Id") %>' OnCommand="Get_carte"><%# Container.FindControl("lnk").ClientID %> <%# DataBinder.Eval(Container.DataItem, "Name") %> - <%# DataBinder.Eval(Container.DataItem, "id") %> - <%# DataBinder.Eval(Container.DataItem, "compteur") %></asp:LinkButton></li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
And my GetCarte Method:
protected void Get_carte(object sender, CommandEventArgs e)
{
LinkButton lnk = (LinkButton)sender;
ViewState["liactive"] = lnk.UniqueID.ToString().Substring(0, lnk.UniqueID.ToString().Length - 4);
lbl_carte.Text = lnk.UniqueID + " " + e.CommandArgument.ToString();
foreach (RepeaterItem rI in Repeater1.Items)
{
if (rI.ItemType == ListItemType.Item || rI.ItemType == ListItemType.AlternatingItem)
{
string liactiv = "";
if (ViewState["liactive"] != null)
liactiv = ViewState["liactive"].ToString();
var li = (HtmlControl)rI.FindControl("li");
if (li.UniqueID.ToString().Substring(0, li.UniqueID.ToString().Length - 3) == liactiv) //Adjust your condition
li.Attributes.Add("class", "active");
else
li.Attributes.Remove("class");
}
}
}
Thanks for your help.
PS: I put ID in ViewState in case of needing the value in another part of my code. I also can replace my substring by lastindexof method.
Code Behind - C# :
You can add runat="server" and id="" to your li, in order to modify in your code behind
void Repeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var li = (HtmlControl)e.Item.FindControl("IdOfYourLI");
if(condition) //Adjust your condition
{
li.Attributes.Add("class", "active");
}
}
}
You can also modify with JavaScript :
You add to element id and use GetElementById method
youIdOfControlLI.className = 'active';
Using jQuery:
jsFiddle working link
Set class="linkButton" to you LinkButtons.
<asp:LinkButton ID="lnk" class="linkButton" />
Use the following jQuery Code to to set the Class on the li:
$(function () {
$(".linkButton").each(function (index) {
$(this).on("click", function () {
$(".linkButton").each(function (index) {
$(this).closest("li").removeClass("active");
});
$(this).closest("li").addClass("active");
});
});
});
Related
I want to know how to Add a UserControl Conditionally to a Repeater Control. I have tried to add it to the placeholder which is in Repeater Control but unable to load the usercontrol. This following code doesn't work.
<asp:Repeater ID="ResultsRepeater" runat="server">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
</asp:PlaceHolder>
</div>
</ItemTemplate>
</asp:Repeater>
public void GetStatus(int i)
{
UserControl uc = new UserControl();
if(i==1)
{
uc = LoadControl("DraftList.ascx") as UserControl;
}
else if(i==2)
{
uc = LoadControl("FinalList.ascx") as UserControl;
}
PlaceHolder p1 = (PlaceHolder)ResultsRepeater.Items[0].FindControl("PlaceHolder1");
p1.Controls.Add(uc);
}
Is there some reason that you don't want to just handle all of this in the aspx? That would be the simplest and cleanest option:
<asp:Repeater runat="server" ID="ResultsRepeater">
<ItemTemplate>
<uc1:DraftList ID="DraftList1" runat="server" Visible='<%# ((int)Eval("Status") == 1)%>' />
<uc2:FinalList ID="FinalList1" runat="server" Visible='<%# ((int)Eval("Status") == 2)%>' />
</ItemTemplate>
</asp:Repeater>
If a control is not visible, (i.e., Visible=false) then no markup is rendered, so coding in this fashion would not create any more work for the server or the client browser, while having the benefit of being much easier to read and providing user control properties at design-time.
You would just need to make sure to register your controls at the top of the page:
<%# Register src="DraftList.ascx" tagname="DraftList" tagprefix="uc1" %>
<%# Register src="FinalList.ascx" tagname="FinalList" tagprefix="uc2" %>
Why don't you try adding it within the repeaters ItemDataBound event? I.e.,
<asp:Repeater ID="ResultsRepeater" OnItemDataBound="ResultsRepeater_ItemDataBound" runat="server">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
</asp:PlaceHolder>
</div>
</ItemTemplate>
</asp:Repeater>
and in the code behind
protected void ResultsRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Panel PlaceHolder1 = (Panel)e.Item.FindControl("PlaceHolder1");
// declare/obtain the value of i given the DataItem
// e.g.,
int i = ((int)e.Item.DataItem); // or however you're getting i
if (i == 1)
{
var uc = LoadControl("~/DraftList.ascx");
PlaceHolder1.Controls.Add(uc);
}
else if (i == 2)
{
var uc = LoadControl("~/FinalList.ascx");
PlaceHolder1.Controls.Add(uc);
}
}
}
Judging by your last comment (to the question) you might need to also make sure you've attached and bound your datasource to the repeater as well. I.e.,
ResultsRepeater.DataSource = dataSource; //whatever your datasource is e.g., datatable, IEnumerable list etc
ResultsRepeater.DataBind();
For example in the backend I'm binding a datable to a repeater and in the front end I'm setting up my repeater as such:
<asp:Repeater ID="Repeater1" runat="server" onitemdatabound="Repeater1_ItemDataBound">
<ItemTemplate>
<div class="user">
Name: <%# DataBinder.Eval(Container, "DataItem.Name")%>
Email: <%# DataBinder.Eval(Container, "DataItem.Email")%>
Active: <%# DataBinder.Eval(Container, "DataItem.Active")%>
Status: <%# DataBinder.Eval(Container, "DataItem.Status")%>
</div>
</ItemTemplate>
</asp:Repeater>
So the output for "name" and "email" are fine. However "Active" and "Status" print out an integer code that I would like to change to a more descriptive string based on a reference table I have.
I'm guessing I can do this on the "ItemDataBound" event of the repeater, but I'm stuck on what my next step should be, namely checking the two fields that I need to modify and change them.
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
//Do modifications here
}
}
You can either
Handle the formatting in the ItemDataBound event
Create public methods in your Page or WebUserControl class to handle the formatting.
Using option 1 will require you to declare a control such as a label to store the value for each field like so:
<asp:Repeater ID="Repeater1" runat="server" onitemdatabound="Repeater1_ItemDataBound">
<ItemTemplate>
<div class="user">
<asp:Label ID="ActiveLabel" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Name")%>'></asp:Label>
</div>
</ItemTemplate>
</asp:Repeater>
Then in your ItemDataBound event you can find the control and set its value as required.
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Label activeLabel = (Label)e.Item.FindControl("ActiveLabel");
//Format label text as required
}
}
Using option 2 will require you to create a server side publicly accessible method which you can call like so:
<asp:Repeater ID="Repeater1" runat="server" onitemdatabound="Repeater1_ItemDataBound">
<ItemTemplate>
<div class="user">
Active: <%# FormatActive((string)DataBinder.Eval(Container, "DataItem.Active")) %>
</div>
</ItemTemplate>
</asp:Repeater>
Then define a method like so:
public string FormatActive(string input)
{
//Format as required
//Return formatted string
}
I prefer creating format methods called in the markup rather than handling ItemDataBound.
<asp:Repeater ID="Repeater1" runat="server" onitemdatabound="Repeater1_ItemDataBound">
<ItemTemplate>
<div class="user">
Name: <%# DataBinder.Eval(Container, "DataItem.Name")%>
Email: <%# DataBinder.Eval(Container, "DataItem.Email")%>
Active: <%# FormatActive((int)DataBinder.Eval(Container, "DataItem.Active"))%>
Status: <%# FormatStatus((int)DataBinder.Eval(Container, "DataItem.Status"))%>
</div>
</ItemTemplate>
</asp:Repeater>
Then in your code behind:
protected static FormatActive(int active)
{
return "Formated Active String...";
}
protected static FormatStatus(int status)
{
return "Formated StatusString...";
}
<asp:Repeater ID="Repeater1" runat="server" onitemdatabound="Repeater1_ItemDataBound">
<ItemTemplate>
<div class="user">
Active: <asp:label id="lblActive" Text='<%# DataBinder.Eval(Container, "DataItem.Active")%>' runat="server" />
</div>
</ItemTemplate>
</asp:Repeater>
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
//Do modifications here
YourObjectName person = (YourObjectName)e.Item.DataItem;
//you can now ref the object this row is bound to
//example find a dom element
Label lblActive= (Label)e.Item.FindControl("lblActive");
if(person.Active == 2)
{
lblActive.Text = "This is great";
}
}
}
You could do something like:
<%# (int)DataBinder.Eval(Container, "DataItem.Active") == 0 ? "Active" : "Inactive" %>
no need to use the itemdatabound. Just add a method in your itemtemplate to do the conversion with the dataitem.active as parameter. Add a label and do the following:
Text='<%# String.Format("{0}",Conversion(Eval("dataitem.active")))%>'
Conversion is then a method you leave in your code behind or utility class where you do the conversion.
I'm using repeater to create dynamic ul li list
Is it possible to control class whether item is first or last?
Something like:
class="<%# if(Container.ItemIndex == 0)
{
class = ...
}
) %>"
by the way what does it really mean: <%# in ASP.NET
What is the difference between <%# and <%=?
It is quite easy to determine whether the item is first or not (Container.ItemIndex == 0), but to determine whether the element is last or not you have to use a custom property which will be initialized right with data binding:
protected int ItemCount { get; set; }
Here is a repeater example:
<asp:Repeater runat="server" ID="repeater">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li class="<%# GetItemClass(Container.ItemIndex) %>">
<%# Container.DataItem %>
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
here is an example of data binding:
public override void DataBind()
{
var data = new string[] { "first", "second", "third" };
this.ItemCount = data.Length;
repeater.DataSource = data;
repeater.DataBind();
}
and finally a helper method:
protected string GetItemClass(int itemIndex)
{
if (itemIndex == 0)
return "first";
else if (itemIndex == this.ItemCount - 1)
return "last";
else
return "other";
}
This will produce:
<ul>
<li class="first">
first
</li>
<li class="other">
second
</li>
<li class="last">
third
</li>
</ul>
I typically use something like the following:
<asp:Repeater ID="rptItems" runat="server" ViewStateMode="Disabled">
<ItemTemplate>
<li<%# Container.ItemIndex == ((IList)((Repeater)Container.Parent).DataSource).Count-1 ? " class='last'" : ""%>>
...
</li>
</ItemTemplate>
</asp:Repeater>
If possible, I'd recommend using something like jQuery for this as it makes implementing this type of functionality very easy. For example, you could have something like this:
<asp:Repeater id="MyRepeater" runat="server">
<HeaderTemplate><table class="MyRepeater"></HeaderTemplate>
<FooterTemplate></table></FooterTemplate>
<ItemTemplate><tr><td>My Data</td></tr></ItemTemplate>
</asp:Repeater>
$("table.MyRepeater tr:last").attr("class", "last");
Try somwthing like this, if you are not using jQuery
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Label ID="Label1" CssClass='<%# Container.ItemIndex == 0 ? "first" : "notFirst" %>' runat="server" Text="Label"></asp:Label>
</ItemTemplate>
</asp:Repeater>
I modified nelsestu's solution and came up with:
<%# Container.ItemIndex == ((System.Data.DataTable)((Repeater)Container.Parent).DataSource).Rows.Count-1 ? "</div>" : string.Empty %>
As for your question on the difference between <%= and <%#, please see the following links:
Code Render Blocks:
http://msdn.microsoft.com/en-us/library/k6xeyd4z(v=vs.71).aspx
Data Binding Expression Syntax:
http://msdn.microsoft.com/en-us/library/bda9bbfx(v=vs.71).aspx
I wasn't able to use Alex's answer directly. Here are the modifications I made that worked for me. Using Alex's "repeater example" for the asp:Repeater tag, use this in the code behind:
private string[] data = new string[] { "first", "second", "third" };
protected int ItemCount { get; set; }
private void Page_Load(object sender, EventArgs e)
{
// normally one would fetch the data here right before binding like this:
// data = SomeService.SomeMethodToGetData();
repeater.DataSource = data;
repeater.DataBind();
}
public override void DataBind()
{
ItemCount = data.Count();
}
protected string GetItemClass(int itemIndex)
{
if (itemIndex == 0)
return "first";
else if (itemIndex == this.ItemCount - 1)
return "last";
else
return "other";
}
I usually do it like this for the last item
Public m_recordCount As Integer
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ltrlTitle.Text = m_title
Using Context As New MyEntities
Dim m_lst = Context.getHotRecords(m_location).ToList
m_recordCount = m_lst.count()
rptListings.DataSource = m_lst
rptListings.DataBind()
End Using
End Sub
and here is how I use it in HTML markup
<div <%# IIf(m_recordCount - 1 = Container.ItemIndex, "class='clearBorder'", "")%>>
For those needing this in VB, here's what works for me.
<span runat="server" class='divider'
Visible="<%# Container.ItemIndex < DirectCast(DirectCast(Container.Parent,Repeater).DataSource,List(Of IList)).Count()-1 %>">|</span>
I needed a divider to show for all items except for the last one.
If your are using controls within your ItemTemplate you can do something like the following, add OnItemDataBound event.
<asp:Repeater ID="RptId" runat="server" OnItemDataBound="OnItemDataBound">
<ItemTemplate>
<asp:Panel runat="server" ID="PnlCtrlItem">
<%#Eval("Content") %>
</asp:Panel>
</ItemTemplate>
</asp:Repeater>
protected void OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemIndex == 0)
((Panel) e.Item.FindControl("PnlCtrlItem")).CssClass = "first";
//or the following to have your control indexed
((Panel) e.Item.FindControl("PnlCtrlItem")).CssClass = string.Format("item-{0}",e.Item.ItemIndex);
}
aspx file
<ul>
<asp:Repeater runat="server" ID="rpt1" OnItemDataBound="rpt1_ItemDataBound">
<HeaderTemplate>
<li><a id="a1" href="javascript:void(0);" runat="server">Text</a></li>
</HeaderTemplate>
<ItemTemplate>
<li><a id="name" runat="server" href="javascript:void(0);">
<%# Eval("Name").ToString() %></a>
<asp:Label runat="server" ID="lblID" Visible="false" Text='<%#Eval("ID") %>'></asp:Label>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
Now there are five items in the ItemTemplate of this repeater..what i want is to set class of each of the anchor tags as "mySprite id1,mySprite id2 , mySprite id3 and so on.."
for that I did this in code behind...
for (int i = 1; i < 6; i++)
{
Name.Attributes.Add("class", "sprite id" + i);
}
Now when I view page source, ALL my anchor tags have got class set as class="sprite id5"
what am I doing wrong ? Plz help..thnx
Try something like this in your OnItemDataBound event handler:
protected void rpt1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
{
HtmlAnchor nameAnchor = (HtmlAnchor)e.Item.FindControl("name");
nameAnchor.Attributes.Add("class", "sprite id" + (e.Item.ItemIndex + 1));
}
}
At the end of the for loop, Name has the value "id5". The for loop in code behind is evaluated first, then the end result value of "id5" is bound to the repeater (5 times).
Since the <asp:Repeater> is designed to display data from a DataSource, you could add the class names "id1, id2, id3, id4, id5, etc." to each row of your data, and bind that field to the class name.
Or, unless you are using GUIDs, you can Concat() the id field of the table to "id"
I know how to use a simple If statement wrapped in the <%# tags to hide something, but I don't know how to do it in a repeater when I need to access Container.DataItem, as in I need the dataItem currently being 'repeated'
eg
if (CurrentValidationMessage.Link != "")
{
show a hyperlink
}
Markup:
<asp:Repeater ID="repValidationResults" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<a href='<%# ((MttImportValidationMessage)Container.DataItem).EditLink %>'> Link to erroneous Milestone </a>
<%# ((MttImportValidationMessage)Container.DataItem).Message %>
<br />
</ItemTemplate>
</asp:Repeater>
It might be more maintainable if you just tagged the controls in the repeater with id's and runat='server' and reference the DataItem in the ItemDataBound event by using e.Item.DataItem.
Then use e.Item.FindControl to reference your controls in the ItemTemplate and perform your logic.
protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
Domain.Employee employee = (Domain.Employee)e.Item.DataItem;
Control myControl = (Control)e.Item.FindControl("controlID");
//Perform logic
}
}
use ItemDataBound Event with repeater, and make the "a" tag with a runat="server" property and ID
protected void repValidationResults_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RepeaterItem item = e.Item;
if (item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.Item)
{
HyperLink link = (HyperLink) item.FindControl("link");
//Do all your logic here :)
}
}
MarkUp:
<asp:Repeater ID="repValidationResults" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<a runat="server" ID="link"> Link to erroneous Milestone </a>
<%# ((MttImportValidationMessage)Container.DataItem).Message %>
<br />
</ItemTemplate>
</asp:Repeater>