Accessing Textboxes in Repeater Control - c#

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

Related

BackColor in codebehind only changing color directly around text

So I have a list view with a C# code behind. I'm attempting to set the background of the cell if the value of JobsCovered is > 1000 (for example) in my code behind. But instead of setting the background color of the entire cell, it only sets the background immediately around the text only. I have to be missing something very simple.
HTML:
<ItemTemplate>
<td runat="server" style="background-color:black;color: white;text-align:center;">
<asp:Label ID="PartDescriptionLabel" runat="server" Text='<%# Eval("PartDescription") %>' />
<br />
<asp:Label ID="PartNumberLabel" runat="server" Text='<%# Eval("PartNumber") %>' />
<br />
<div id="JobsCoveredBox" style="height:60px; line-height:60px">
<asp:Label ID="JobsCoveredLabel" runat="server" Text='<%# Eval("JobsCovered") %>' />
</div>
</td>
</ItemTemplate>
Code Behind:
protected void RepackOSR_ItemDataBound(object sender, ListViewItemEventArgs e)
{
// Retrieve the current item.
ListViewItem item = e.Item;
Label JobsCoveredLabel;
// Verify if the item is a data item.
if (item.ItemType == ListViewItemType.DataItem)
{
JobsCoveredLabel = (Label)e.Item.FindControl("JobsCoveredLabel");
System.Data.DataRowView rowView = e.Item.DataItem as System.Data.DataRowView;
//Store the value of "JobsCovered" from data source
Int32 currentJobCovered = Convert.ToInt32(rowView["JobsCovered"].ToString());
if (currentJobCovered > 1000)
{
//Why won't this change the entire background of the cell?
JobsCoveredLabel.BackColor = Color.Green;
}
}
}
It only does this...
Not the entire background
You want of course to color the div background I assume?
thus you need to tag the div as server control.
So, try this:
<div id="JobsCoveredBox" runat="server" style="height:60px; line-height:60px">
So, now we can grab/get the div say like this in your row data bind event
HtmlGenericControl mydiv = (HtmlGenericControl)e.Item.FindControl("JobsCoveredBox");
mydiv.Style.Add("background-color", "aliceblue");

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;

need to change class in repeater elements

i have a repeater:
<ul>
<asp:Repeater ID="Repeater4" runat="server" DataSourceID="SqlDataSource5" onitemcommand="Repeater4_ItemCommand">
<ItemTemplate>
<li class="sports_menu1">
<asp:LinkButton ID="LinkButton1" runat="server" class="selected onclick="sideMenuSports1_Click">
<%#Eval("iconURL")%>
</asp:LinkButton></li>
</ItemTemplate>
</asp:Repeater>
</ul>
and i want to handle all the buttons in the same function:
protected void sideMenuSports1_Click(object sender, EventArgs e)
{
changeDataSources(); /*-----> this function supose to derict to URL(in a div on the same page) acording the id of the item of the repeater */
removeAllClasses(); /*this supose to remove all class named selected from the element in the <asp:button> element */
((LinkButton)sender).Attributes.Add("class", "selected");
}
to sumerise, what i need is:
i need to remove the class "selected" in all the repeater <asp:button> elements, then add it only to the element the user clicked
each button clicked redirect to other URL ,how i pass the button the id of the repeater element?
Had the same problem, solved it like this:
.aspx part:
<asp:Repeater ID="itemsRepeater" runat="server" OnItemCommand="itemsRepeater_ItemCommand">
<ItemTemplate>
<li>
<asp:LinkButton id="location_button" CommandArgument='<%# Eval("Key") %>' Text='<%# Eval("Value") %>' runat="server"></asp:LinkButton>
</li>
</ItemTemplate>
</asp:Repeater>
code-behind part:
protected void itemsRepeater_ItemCommand(object source, RepeaterCommandEventArgs e)
{
// for the sample purpose, setting the value here - replace it with your own
int locationId = 2;
// looping through all the repeater items (buttons)
foreach (RepeaterItem i in ((Repeater)source).Items)
{
// finding the repeater items having ID set to "location_button"
LinkButton btn = (LinkButton)i.FindControl("location_button");
// custom class added when location matches button's CommandArgument
if (btn.CommandArgument == locationId.ToString())
btn.CssClass = "button_main active";
else
btn.CssClass = "button_main";
}
}

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.

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"

Categories

Resources