ASP.NET - Nested Repeaters - c#

I have a repeater for different updates identified by "Update_ID". Each "Update_ID" has a number of images associated to it.
Therefore, I decided to nest a repeater for the images inside the repeater for updates.
The problem is that the image repeater never shows up, even if there is data to show.
Here is the code in ASP.NET:
<asp:Repeater ID="RepeaterUpdates" runat="server" onitemcommand="RepeaterUpdates_ItemCommand">
<ItemTemplate>
<div style="border: thin solid #808080">
<table id="TableUpdates_Repeater" runat="server" style="width:100%; margin:auto; background-image:url(Resources/Icons/white-background.gif)">
<tr>
<td style="width:25%">
<br />
<asp:Label ID="LabelUpdateID_Repeater" runat="server" Text="Update ID" Enabled="false"></asp:Label>
<asp:TextBox ID="TextBoxUpdateID_Repeater" runat="server" Width="50px" Text='<%# Eval("Update_ID") %>' Enabled="false"></asp:TextBox>
</td>
</tr>
</table>
<asp:Repeater ID="RepeaterImages" runat="server">
<ItemTemplate>
<label>Hello</label>
<asp:TextBox Text='<%# DataBinder.Eval(Container.DataItem,"Image_ID") %>' runat="server"></asp:TextBox>
</ItemTemplate>
</asp:Repeater>
</div>
</ItemTemplate>
</asp:Repeater>
Here is the code-behind:
protected void RepeaterUpdates_ItemCommand(object source, RepeaterCommandEventArgs e)
{
SqlConnection conn5 = new SqlConnection(connString);
SqlDataReader rdr5;
RepeaterItem item = e.Item;
TextBox Update_ID = (TextBox)item.FindControl("TextBoxUpdateID_Repeater");
try
{
conn5.Open();
SqlCommand cmd5 = new SqlCommand("SelectImages", conn5);
cmd5.CommandType = CommandType.StoredProcedure;
cmd5.Parameters.Add(new SqlParameter("#update_id", Update_ID.Text));
rdr5 = cmd5.ExecuteReader();
if ((item.ItemType == ListItemType.Item) || (item.ItemType == ListItemType.AlternatingItem))
{
Repeater ImageRepeater = (Repeater)item.FindControl("RepeaterImages");
ImageRepeater.DataSource = rdr5;
ImageRepeater.DataBind();
}
}
finally
{
conn5.Close();
}
}
As previously stated, the child repeater never shows up, even if there is data to display. How can I solve this problem please? Thanks

Rather than onitemcommand, call OnItemDataBound
Change RepeaterCommandEventArgs to RepeaterItemEventArgs

In addition to #Curt. Below is the code.
Code Behind
class Images
{
public int Image_ID;
}
protected void RepeaterUpdates_ItemCommand(object source, RepeaterCommandEventArgs e)
{
RepeaterItem item = e.Item;
TextBox Update_ID = (TextBox)item.FindControl("TextBoxUpdateID_Repeater");
try
{
conn5.Open();
using (SqlCommand cmd5 = new SqlCommand("SelectImages", conn5))
{
cmd5.CommandType = CommandType.StoredProcedure;
cmd5.Parameters.Add(new SqlParameter("#update_id", Update_ID.Text));
List<Images> Lst = new List<Images>();
using (SqlDataReader rdr5 = cmd5.ExecuteReader())
{
while (rdr5.Read())
{
Lst.Add(new Images { Image_ID = Convert.ToInt16(rdr5["Image_ID"]) });
}
if ((item.ItemType == ListItemType.Item) || (item.ItemType == ListItemType.AlternatingItem))
{
Repeater ImageRepeater = (Repeater)item.FindControl("RepeaterImages");
ImageRepeater.DataSource = Lst;
ImageRepeater.DataBind();
}
}
}
}
finally
{
conn5.Close();
}
}
HTML
You should Register ItemBoundData Event
<asp:Repeater ID="rp" runat="server" onitemdatabound="rp_ItemDataBound">
<ItemTemplate></ItemTemplate>
</asp:Repeater>
protected void rp_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
}

Related

How to get a radio button excluyent in a repeater element?

I have a repeater using for getting an image nad a radio button on the bottom. I want to achieve a combination of this radio button (repeater speaking) with the property of autoexcluyent feature. How can I achieve it?
As far as I got ...
<asp:Repeater runat="server" ID="repeater1">
<ItemTemplate>
<div class="col-xs-12 col-sm-4 col-md-3">
<asp:Image ID="img" runat="server" ImageUrl="<%#GetRutaImagen(Eval("id").ToString())%>" />
<span>
<asp:RadioButton runat="server" ID="rb1" Text='<%#Eval("description").ToString()%>' GroupName="nameGroup"/>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
With this code I am getting a one radio button per each image but no one autoexcuyent even I am using GroupName property
USING NET FRAMEWORK 4.6.2.
I don't know if easy way to manage this situation however you can manage by below code. It will be good to wrap your contents into update panel so you can prevent page refresh on checkbox changed.
Additionally, IsChecked property being used to initialize checked on page load. You can remove if not required.
.ASPX
<asp:Repeater runat="server" ID="repeater1">
<ItemTemplate>
<div class="col-xs-12 col-sm-4 col-md-3">
<span>
<asp:RadioButton runat="server" ID="rb1" Checked='<%# Eval("IsChecked") %>' AutoPostBack="true" OnCheckedChanged="rb1_CheckedChanged" Text='<%#Eval("description").ToString()%>' />
</span>
</div>
</ItemTemplate>
</asp:Repeater>
.CS
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<test1> lst = new List<test1>();
lst.Add(new test1() { Id = 1, description = "R1", IsChecked = false });
lst.Add(new test1() { Id = 3, description = "R2", IsChecked = true });
lst.Add(new test1() { Id = 2, description = "R3", IsChecked = false });
lst.Add(new test1() { Id = 4, description = "R4", IsChecked = false });
repeater1.DataSource = lst;
repeater1.DataBind();
}
}
protected void rb1_CheckedChanged(object sender, EventArgs e)
{
foreach (RepeaterItem item in repeater1.Items)
{
(item.FindControl("rb1") as RadioButton).Checked = false;
}
(sender as RadioButton).Checked = true;
}
After researching between SOF and a few forums I implemented a quite right solution using JS. I am handling another problem related with OnCheckedChanged´s event on RadioButton...
But the initial issue is fixed.
Forum Solution
I am posting the solution that works for me, using as base as a help coming from a forum, hoping it helps others as well with this bug.
REPEATER.
<asp:Repeater runat="server" ID="repeater1" OnItemDataBound="repeater1_ItemDataBound">
<ItemTemplate>
<div class="col-xs-12 col-sm-4 col-md-3">
<asp:Image ID="img" runat="server" ImageUrl="<%#GetRutaImagen(Eval("id").ToString())%>" />
<span>
<asp:RadioButton runat="server" ID="rb1" Text='<%#Eval("description").ToString()%>' GroupName="nameGroup" OnCheckedChanged="rb1_CheckedChanged"/>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
JS
<script>
function SetUniqueRadioButton(nameregex, current) {
for (i = 0; i < document.forms[0].elements.length; i++) {
elm = document.forms[0].elements[i]
if (elm.type == 'radio') {
elm.checked = false;
}
}
current.checked = true;
}
</script>
BACKEND
protected void repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
RadioButton rbLogoSeleccionado = (RadioButton)e.Item.FindControl("rb1");
string script = "SetUniqueRadioButton('repeater1.*nameGroup',this)";
rbLogoSeleccionado.Attributes.Add("onclick", script);
}
}
catch (Exception ex)
{
PIPEvo.Log.Log.RegistrarError(ex);
throw;
}
}

Using Datalist Items within a nested repeater

I have this code for a blog which is nesting a repeater control within a datalist.
I'm trying to assign the alt tags of the repeater control images to be the title of the post coming through the datalist however, it will not let me though this because it has a different data source.
Any suggestions as to how I can do this?
Here's my code:
<asp:DataList runat="server" ID="DataList1" ItemStyle-CssClass="row1BackgroundBlock" OnItemDataBound="DataList1_ItemDataBound" >
<ItemTemplate>
<!-- <%#Eval("PostId")%> post -->
<div class="dateBox"><asp:Label ID="Label1" runat="server" ForeColor="#ffffff" Font-Bold="False" Text='<%# Eval("PublicationDate","{0:dd/MM/yyyy}") %>' CssClass="postmetadata"></asp:Label></div>
<div class="roundPanelStack">
<h2><asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Engine2010.Blog.BlogLinksManager.GetFullPostsLinks((int)Eval("PostId"), (object)Eval("FURL")) %>'><%# Eval("Title") %></asp:HyperLink></h2>
<ul><li class="postBy">Posted in <%#Eval("CategoryName")%> by <%#Eval("Author")%></li><li class="last">{<%# Engine2010.Blog.PostComment.GetAllByPostId(int.Parse(Eval("PostId").ToString()), 766).Rows.Count.ToString()%> comments}</li></ul>
<div class="thumbWindow">
<div style="border:7px solid #fff;display:block;height:95px;left:1px;position:absolute;top:1px;width:95px;z-index:5;"></div>
<asp:Repeater ID="repImgs" runat="server">
<ItemTemplate>
<img class="thumb_view" src="/uploads/images/Blog/<%# Eval("Directory").ToString().Substring(Eval("Directory").ToString().LastIndexOf("\\")+1) %>/<%# Eval("Name") %>" alt="" border="0" width="143" height="143" />
</ItemTemplate>
</asp:Repeater>
<asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible="false">
<img src="/includes/images/general/default.jpg" alt="Default" border="0" width="110" height="110" />
</asp:PlaceHolder>
</div>
<p>
<asp:Label ID="Label2" runat="server" Text='<%#CommonFunctions.Remove_HTML_Tags(Eval("Description").ToString()) %>' CssClass="entry"></asp:Label>
</p>
<div class="linksMore">
<asp:HyperLink ID="FullStoryLink" runat="server" NavigateUrl='<%# Engine2010.Blog.BlogLinksManager.GetFullPostsLinks((int)Eval("PostId"), (object)Eval("FURL")) %>' CssClass="fullstory">Read Full Post</asp:HyperLink><a class="spacer"> // </a><asp:HyperLink ID="CommentsLink" runat="server" NavigateUrl='<%# Engine2010.Blog.BlogLinksManager.GetFullPostsLinks((int)Eval("PostId"), (object)Eval("FURL")) + "#comment" %>' CssClass="comments">Comment</asp:HyperLink>
</div>
</div>
<!-- /first post -->
</ItemTemplate>
</asp:DataList>
Backend:
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater repImages = (Repeater)e.Item.FindControl("repImgs"); // Child repeater with images for room
string amenText = ((DataRowView)e.Item.DataItem).Row.ItemArray[7].ToString();
DirectoryInfo folderBr = new DirectoryInfo(Server.MapPath("~/uploads/images/Blog/") + amenText);
// List<Engine2010.ImageObj> imageObjs = folderBr.GetImagesInPath();
if (folderBr.Exists)
{
repImages.DataSource = folderBr.GetFiles("thumb*.*"); // Bind room images to child repeater
repImages.DataBind();
if (repImages.Items.Count == 0)
{
PlaceHolder placeholder1 = (PlaceHolder)e.Item.FindControl("PlaceHolder1");
placeholder1.Visible = true;
}
}
else {
PlaceHolder placeholder1 = (PlaceHolder)e.Item.FindControl("PlaceHolder1");
placeholder1.Visible = true;
}
}
}
In the ItemDataBound event of your DataList1 after binding repImages repater control, iterate through each item by using RepeaterItem and then find your img control and assign title in alt tag like this -
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater repImages = (Repeater)e.Item.FindControl("repImgs");
string amenText = ((DataRowView)e.Item.DataItem).Row.ItemArray[7].ToString();
DirectoryInfo folderBr = new DirectoryInfo(Server.MapPath("~/uploads/images/Blog/") + amenText);
if (folderBr.Exists)
{
repImages.DataSource = folderBr.GetFiles("thumb*.*"); // Bind room images to child repeater
repImages.DataBind();
if (repImages.Items.Count == 0)
{
PlaceHolder placeholder1 = (PlaceHolder)e.Item.FindControl("PlaceHolder1");
placeholder1.Visible = true;
}
// Iterate thru each item of your child repeate control.
foreach (RepeaterItem repeaterItem in repImages.Items)
{
if (repeaterItem.ItemType == ListItemType.Item ||
repeaterItem.ItemType == ListItemType.AlternatingItem)
{
((HtmlImage)(repeaterItem.FindControl("imgId"))).Alt = amenText; // Assume amenText is the title of your post
}
}
}
else
{
PlaceHolder placeholder1 = (PlaceHolder)e.Item.FindControl("PlaceHolder1");
placeholder1.Visible = true;
}
}
}
good luck...

Edit Textbox in Repeater

I have a repeater with a textbox inside. I am trying to edit the information inside the textbox, retrieve the new data, and write to the DB. With my code its giving me the original info that was in the box. Not the new information that I have added. Here is my code
html:
<asp:LinkButton id="saveReviewLinkButton" text="Save" runat="server" onCommand="saveReviewLinkButton_OnCommand" />
<table>
<asp:Repeater id="ReviewRepeater" runat="server" onItemDataBound="ReviewRepeater_ItemDataBound">
<itemtemplate>
<tr >
<td ><asp:TextBox id="titleLabel" runat="server" width="200px" textMode="MultiLine"/></td>
</tr>
</itemtemplate>
</table>
c#:
protected void ReviewRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
{
Review review = (Review)e.Item.DataItem;
TextBox titleLabel = (TextBox)e.Item.FindControl("titleLabel");
titleLabel.Text = review.Title;
}
}
protected void saveReviewLinkButton_OnCommand(object sender, EventArgs e)
{
TextBox titleLabel = new TextBox();
foreach (RepeaterItem dataItem in ReviewRepeater.Items)
{
titleLabel = (TextBox)dataItem.FindControl("titleLabel");
string newInfo = titleLabel.Text;
}
}
Please make sure, you are binding the data to the repeater by checking in page load
if(!IsPostBack)
BindData();

Repeater in ASP.net

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.

Finding controls in repeater on commandargument

I have a repeater:
<asp:Repeater ID="rpt_Items" OnItemCommand="rpt_Items_ItemCommand" runat="server">
<ItemTemplate>
<div class="item">
<div class="fr">
<asp:TextBox ID="tb_amount" runat="server">1</asp:TextBox>
<p>
<%# Eval("itemPrice") %>
</p>
<asp:LinkButton ID="lb_buy" CommandName="buy" runat="server">buy</asp:LinkButton>
</div>
<asp:HiddenField ID="hdn_ID" Value='<%# Eval("itemID") %>' runat="server" />
</div>
</ItemTemplate>
</asp:Repeater>
On the repeater commandargument i want to get the textbox and the hiddenfield but how do i do this?
protected void rpt_Items_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandName == "buy")
{
//ADD ITEM TO CART
Response.Write("ADDED");
Product getProduct = db.Products.FirstOrDefault(p => p.ProductID == id);
if (getProduct != null)
{
CartProduct product = new CartProduct()
{
Name = getProduct.ProductName,
Number = amount,
CurrentPrice = getProduct.ProductPrice,
TotalPrice = amount * getProduct.ProductPrice,
};
cart.AddToCart(product);
}
}
}
Thanks a bunch!
You don't have to pass it through the Command Argument, you can use e.Item.FindControl() inside your rpt_Items_ItemCommand method, as in:
TextBox tb_amount = (TextBox)e.Item.FindControl("tb_amount");
HiddenField hdn_ID = (HiddenField)e.Item.FindControl("hdn_ID");

Categories

Resources