Finding controls in repeater on commandargument - c#

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");

Related

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...

C# delete item from listview from control outside listview

From a listview control, when checkboxes are checked and a button is clicked from outside the listview, I need to be able to delete the items that have been checked. Here's the listview:
EDIT
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) return;
var notes = (from n in db.Notes
select n).OrderBy(n => n.FiscalYear).ThenBy(n => n.Period);
notesListView.DataSource = notes;
notesListView.DataBind();
}
<asp:ListView ID="notesListView" ItemPlaceholderID="itemPlaceholder" runat="server">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<asp:CheckBox ID="checkNote" runat="server" />
<div><%# Eval("Period") %></div>
<div><%# Eval("FiscalYear") %></div>
<div><%# Eval("Account") %></div>
<div class="wrap"><%# Eval("Description") %></div>
</ItemTemplate>
<EmptyDataTemplate>
<div>No notes have been submitted.</div>
</EmptyDataTemplate>
</asp:ListView>
<br />
<asp:Button ID="deleteNotes" CssClass="deleteButton" Text="Delete Notes" runat="server" OnClick="deleteNotes_Click" />
Here's the code behind:
protected void deleteNotes_Click(object sender, EventArgs e)
{
foreach (ListViewItem item in notesListView.Items)
{
// I know this is wrong, just not sure what to do
if (notesListView.SelectedIndex >= 0)
{
CheckBox ck = (CheckBox)item.FindControl("checkNote");
if (ck.Checked)
{
var index = item.DataItemIndex; // the item row selected by the checkbox
// db is the datacontext
db.Notes.DeleteOnSubmit(index);
db.SubmitChanges();
}
}
else
{
errorMessage.Text = "* Error: Nothing was deleted.";
}
}
}
You need to find the object before deleting it. To do so, I would add a hiddenfield to store NoteID like this:
<asp:HiddenField ID="hdnId" Value='<%#Eval("Id")%>' runat="server" />
<asp:CheckBox ID="checkNote" runat="server" />
... ... ...
And in my code I am finding the note by ID and deleting that note (You may use any other unique field instead of ID). My code may look like this:
... ... ...
int id = 0;
var hdnId = item.FindControl("hdnId") as HiddenField;
CheckBox ck = (CheckBox)item.FindControl("checkNote");
//I would check null for ck
if (ck != null && ck.Checked && hdnId != null && int.TryParse(hdnId.Value, out id)
{
// db is the datacontext
Note note = db.Notes.Single( c => c.Id== id );
db.Notes.DeleteOnSubmit(note );
db.SubmitChanges();
}

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
}
}

ASP.NET - Nested Repeaters

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)
{
}

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.

Categories

Resources