Repeater in ASP.net - c#

I used repeater in asp.net. My problem is don't know how to hide a fields in repeater. There is a regular price and now price if regular price is equal to zero it will hide the fields and if not it will show the value of the regular price. i hope you can help on this.
here my code in asp:
<a href="<%=Utility.GetSiteRoot() %>/BookInfo.aspx?SKU=<%# Utility.SKUMask(Eval("lb_sku").ToString()) %>">
<img width="150px" src='<%# Eval("lb_picturepath")%>'>
</td>
<td valign="top">
<asp:Label ID="lb_titleLabel" runat="server" CssClass="center-head" Text='<%# Eval("lb_title") %>' />
<p><asp:Label ID="lb_descriptionLabel" runat="server" Text='<%# Eval("lb_description") %>' /></p>
<div class="price"><%# "Price: " + decimal.Round((decimal)Eval("lb_sellingprice"),2)%></div>
</td>
</tr>
<tr>
<td></td>
<td>
<a class="addtocart" href="<%=Utility.GetSiteRoot() %>/AddToCart.aspx?SKU=<%# Utility.SKUMask(Eval("lb_sku").ToString()) %>" >Add To Cart</a>
<a href="<%=Utility.GetSiteRoot() %>/BookInfo.aspx?SKU=<%# Utility.SKUMask(Eval("lb_sku").ToString()) %>" class="readmore">
View Details
</a></td>
thanks!

You would need to handle the OnItemDataBound event, and then change the visibility of the control. An example of this is shown below:
ASPX Page
<asp:Repeater ID="MyRepeater" OnItemDataBound="MyRepeater_OnItemDataBound" runat="server">
<ItemTemplate>
<asp:Label ID="RegularPriceLabel" runat="server" />
<br/>
<asp:Label ID="BuyNowPriceLabel" runat="server" />
</ItemTemplate>
</asp:Repeater>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MyRepeater.DataSource = GetDataSource();
MyRepeater.DataBind();
}
}
protected void MyRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// This will be your data object
MyEntity o = (MyEntity) e.Item.DataItem;
// Get the labels
Label RegularPriceLabel = (Label) e.Item.FindControl("RegularPriceLabel");
Label BuyNowPriceLabel = (Label) e.Item.FindControl("BuyNowPriceLabel");
// Only show regular price if it is set
RegularPriceLabel.Visible = (o.RegularPrice > 0);
// Populate labels
RegularPriceLabel.Text = o.RegularPrice.ToString();
BuyNowPriceLabel.Text = o.BuyNowPrice.ToString();
}
}

I would take a look at the ItemDataBound event of the Repeater. It will fire for every item in the repeater and allow you to do any code-behind (like hiding labels) more easily.
Edit: For your specific example, since you are formatting the price as well, it may be easier to just call a custom method to to render the price, like so:
ASPX:
<%#RenderPrice((decimal)Eval("lb_sellingprice"))%>
Method:
protected string RenderPrice(decimal price) {
if (price > 0) {
return "Price: $" + decimal.Round(price);
} else {
return string.Empty;
}
}
It's quick-and-dirty but it works.

Related

Get a value from Repeater in code-behind

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="EntityDataSourceTeklifler">
<ItemTemplate>
<div class="panel panel-primary">
<div class="panel-body">
<strong>Teklif Kodu:</strong> <%#Eval("TeklifId") %><br />
<strong>Teklif Tarihi:</strong> <%#Eval("TeklifTarih") %><br />
<strong>Teklifi Hazırlayan:</strong> <%#Eval("Name") %> <%#Eval("Surname") %><br />
<strong>Firma Adı:</strong> <%#Eval("FirmaAdi") %><br />
<strong>Sipariş:</strong> <%#Eval("FUrunId") %><br />
<strong>Teklif Tutarı:</strong> <%#Eval("TeklifTutar") %><br />
</div>
</div>
</ItemTemplate>
</asp:Repeater>
As you can see I have a Repeater and it displays my data without a problem. I need to access TeklifIds in code-behind. I am going to make something like:
if(TeklifId == 1)
{
//do something
}
else if(TeklifId == 2)
{
//do something else
}
And to do this, I need to get all TeklifId while it is adding to the Repeater.
Ideally you should include the data withing some ASP.NET controls like Label, Textbox control within ItemTemplate tag because it is easy to work with them. But I am not sure why you are adding the normal html tags directly.
Anyways, to find the value you will have to find it within the ItemDataBound control of repeater control but for that you will have to make the strong tag a server control by adding runat="server" attrribute like this:-
<strong id="TeklifId" runat="server">Teklif Kodu:</strong> <%#Eval("TeklifId") %>
Then, add the ItemDataBound event in your repeatre control like this:-
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand"
Finally in the code behind you can find the value like this:-
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem ||
e.Item.ItemType == ListItemType.Item)
{
HtmlGenericControl TeklifId = e.Item.FindControl("TeklifId") as HtmlGenericControl;
string TeklifId = TeklifId.InnerText; //value here
}
}
Place TeklifId in a Label control so that you can use ID and FindControl to get the values like this:
<asp:Label ID="TeklifId" runat="server" Text='<%#Eval("TeklifId") %>'></asp:Label>
And then:
foreach (RepeaterItem item in Repeater1.Items)
{
var TeklifId = (Label)item.FindControl("TeklifId");
if (TeklifId == 1)
{
//do something
}
}
Repeater Code :
<td>
<span runat="server" id="lbBranchname" style="font-style:italic;"><%# Eval("branchname")%></span>
</td>
Code behind : rptBranch_ItemCommand
HtmlGenericControl lbBranchname = e.Item.FindControl("lbBranchname") as HtmlGenericControl;
BranchName = lbBranchname.InnerText;

ASP.NET - ImageButton within a Repeater refuses to raise a click event

No matter what combination I try, the button (ibtnDeleteDiaryEntry) simply will not raise an event although it does seem to do postback as it should. ViewState is turned on by default, read elsewhere that it is sometimes problematic. Also, I've used the Repeater's OnItemCommand property as required. Any kind of help is appreciated.
EDIT: It seems that the problem is somehow connected to the jQuery UI's Accordion Widget. The repeater is located within a div that is used to initialize the accordion. If I remove the div tags surrounding the repeater, the OnItemCommand event gets called. Very weird.
Markup:
<asp:Repeater ID="repAccordion" OnItemCommand="repAccordion_OnItemCommand" runat="server">
<ItemTemplate>
<h3> <%# "Date: " + Eval("date", "{0:d}") %>
<span class="deleteButtonContainer">
<asp:ImageButton ID="ibtnDeleteDiaryEntry" CommandArgument='<%# Eval("diary_entry_id") %>' CommandName="Delete" AlternateText="ibtnDeleteDiaryEntry" ImageUrl="images/remove_item.png" runat="server" />
</span>
</h3>
<div>
<table>
<tr>
<td>
<asp:Label ID="lblText" runat="server" ForeColor="#AA0114" Text="Text:"></asp:Label>
</td>
</tr>
<tr>
<td>
<%# Eval("text") %>
</td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:Repeater>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
_db = new PersonalOrganizerDBEntities();
_diary_entryService = new Diary_EntryService();
_userService = new UserService();
if (!IsPostBack)
{
LoadItems();
}
}
public void LoadItems()
{
long currentUserId = (long) Session["userId"];
User currentUser = _userService.GetById(currentUserId);
Diary_Entry[] diaryEntriesArray =
_diary_entryService.GetAll().Where(current => current.diary_id == currentUser.user_id).ToArray();
if (diaryEntriesArray.Length == 0)
{
noItems.Text = "You currently have no diary entries.";
noItems.Visible = true;
}
else
{
noItems.Visible = false;
}
repAccordion.DataSource = diaryEntriesArray;
repAccordion.DataBind();
}
protected void repAccordion_OnItemCommand(object sender, RepeaterCommandEventArgs e)
{
Response.Write("test");
}
If it doesn't work I would recommend removing OnItemCommand from repeater and adding OnClick event for ImageButton instead. In OnClick event in code behind you can cast 'sender' to ImageButton and read CommandArgument value to get diary_entry_id.

How to get updated Textbox value from Repeater?

I have a repeater control as listed below. It has a textbox control. When a save button is clicked, I need to get the updated text from the textbox. I have the following code; but it gives me the old value when I take the textbox text.
How can we get the updated text?
Code Behind
protected void Save_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in repReports.Items )
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem )
{
string updatedEmail = ((TextBox)item.Controls[5]).Text;
string originalEmail = ((HiddenField)item.Controls[7]).Value;
}
}
}
Control Markup
<div class="repeaterTableBorder">
<asp:Repeater ID="repReports" runat="server">
<ItemTemplate>
<div id="repeaterIdentifier" class="repeaterIdentifier">
<div class="reportTitle">
<%# Eval("ReportName") + ":"%>
<asp:HiddenField ID="hdnLastChangeTime" runat="server" Value= '<%# ((DateTime)Eval("RecordSelectionTime")).ToString("MM/dd/yyyy hh:mm:ss.fff tt")%>' />
<asp:HiddenField ID="hdnReportID" runat="server" Value='<%# Eval("ReportTypeCode")%>' />
</div>
<div class="reportFrequency">
<%# " Frequency - Weekly" %>
</div>
</div>
<div class="reportContent">
<div class="repeaterLine">
<asp:TextBox ID="txtEmailRecipients" runat="server" class="textEdit"
Text='<%# Eval("ExistingRecipients") %>'
TextMode="MultiLine"></asp:TextBox>
<asp:HiddenField ID="hdnOriginalRecipients" runat="server" Value='<%# Eval("ExistingRecipients")%>' />
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
I assume that you are binding the Repeater to it's DataSource also on postbacks. You should do that only if(!IsPostBack). Otherwise the values will be overwritten.
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
// databinding code here
}
}

Adding class to anchor tag inside of repeater in code behind

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"

Accessing Textboxes in Repeater Control

All the ways I can think to do this seem very hackish. What is the right way to do this, or at least most common?
I am retrieving a set of images from a LINQ-to-SQL query and databinding it and some other data to a repeater. I need to add a textbox to each item in the repeater that will let the user change the title of each image, very similar to Flickr.
How do I access the textboxes in the repeater control and know which image that textbox belongs to?
Here is what the repeater control would look like, with a submit button which would update all the image rows in Linq-to-SQL:
alt text http://casonclagg.com/layout.jpg
Edit:
This code works
Just make sure you don't blow your values away by Binding outside of if(!Page.IsPostBack) like me.. Oops.
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div class="itemBox">
<div class="imgclass">
<a title='<%# Eval("Name") %>' href='<%# Eval("Path") %>' rel="gallery">
<img alt='<%# Eval("Name") %>' src='<%# Eval("Path") %>' width="260" />
</a>
</div>
<asp:TextBox ID="TextBox1" Width="230px" runat="server"></asp:TextBox>
</div>
</ItemTemplate>
</asp:Repeater>
And Submit Click:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in Repeater1.Items)
{
TextBox txtName = (TextBox)item.FindControl("TextBox1");
if (txtName != null)
{
string val = txtName.Text;
//do something with val
}
}
}
Have you tried something like following on the button click:-
foreach (RepeaterItem item in Repeater1.Items)
{
TextBox txtName= (TextBox)item.FindControl("txtName");
if(txtName!=null)
{
//do something with txtName.Text
}
Image img= (Image)item.FindControl("Img");
if(img!=null)
{
//do something with img
}
}
/* Where txtName and Img are the Ids of the textbox and the image controls respectively in the repeater.*/
Hope this helps.
.aspx
<asp:Repeater ID="rpt" runat="server" EnableViewState="False">
<ItemTemplate>
<asp:TextBox ID="txtQty" runat="server" />
</ItemTemplate>
</asp:Repeater>
.cs
foreach (RepeaterItem rptItem in rpt.Items)
{
TextBox txtQty = (TextBox)rptItem.FindControl("txtQty");
if (txtQty != null) { Response.Write(txtQty.Text); }
}
Be sure to add EnableViewState="False" to your repeater, otherwise you will get empty string. (That wasted my time, dont waste yours :) )
On postback, you can iterate over the collection of RepeaterItems in repeater.Items. You could then retrieve each TextBox with code such as
TextBox tbDemo = (TextBox)rptr.Items[index].FindControl("textBox");

Categories

Resources