access items in repeater - c#

I have a repeater and I am trying to access labels inside it. Here is my method:
protected void ButtonlarıTemizle()
{
int n = 0;
foreach (RepeaterItem item in Repeater1.Items)
{
n++;
Label lbl = item.FindControl("lblApproved") as Label;
Button btn = item.FindControl("btnAssignApproved") as Button;
if (lbl.Text.Equals("Satışa Dönmüştür"))
{
btn.Visible = false;
lbl.ForeColor = System.Drawing.Color.Blue;
}
}
Response.Write("<script lang='JavaScript'>alert('"+n+"');</script>");
}
I can access inside repeater but here is the problem: I can't access the last item of repeater. I put that 'n' variable to control how many times I turn inside foreach loop and I see that n always gives -1 of item numbers. For example if I have 3 items in repeater, n is 2, if there is 1 item in repeater, n is 0. What am I doing wrong in here ?
Edit: I am writing my .aspx page since it asked
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="EntityDataSourceTeklifler" OnItemCommand="Repeater1_ItemCommand">
<ItemTemplate>
<div class="panel panel-primary">
<div class="panel-body">
<strong>Teklif No.</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>Ürünler:</strong><br />
<%#Eval("TeklifSiparis") %>
<strong>Genel Toplam:</strong> <%#Eval("TeklifTutar") %>$<br />
<strong>Not:</strong><br />
<%#Eval("TeklifNot") %><br />
<strong>Teklif Durumu:</strong> <asp:Label ForeColor="Red" ID="lblApproved" runat="server" Text='<%# CheckIfApproved(Convert.ToBoolean(Eval("Approved"))) %>'></asp:Label><br /><br />
<asp:Button ID="btnAssignApproved" runat="server" Text="Satışa Döndü Olarak İşaretle" CssClass="btn btn-primary" CommandName="Done" CommandArgument='<%# Eval("TeklifId") %>' />
</div>
</div>
</ItemTemplate>
</asp:Repeater>

I am not sure why you explicitly calling a different method but what you are doing can be easily done in ItemDataBound event of repeater control:-
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound"
Then handler it like this:-
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item)
{
Label lbl = e.Item.FindControl("lblApproved") as Label;
Button btn = e.Item.FindControl("btnAssignApproved") as Button;
if (lbl.Text.Equals("Satışa Dönmüştür"))
{
btn.Visible = false;
lbl.ForeColor = System.Drawing.Color.Blue;
}
}
}
Please note there is no need to do any loop on your repeater items. Repeater ItemDataBound event will fire for each item when it is bounded. Also, if you want to have a count simply declare a variable outside this method and increment it inside this event.

Related

ItemCommand not working with repeater and few events

I get a repeater with 3 radio button (grouped in 3 rows by GroupName property) and triggered (per each radio button). My problem is coming when I add a HiddenField to the repeater column and I want to reach this HiddenField through ItemCommand event.
The ItemCommand event is not raising...
(LinkButton click event is working as well)
(If a set CheckedChanged event of radio button they are working fine, but They are not helping because I need to reach the HiddenField)
This my code:
CSHTML
<asp:Repeater runat="server" ID="repeaterImages" OnItemDataBound="repeaterImages_ItemDataBound">
<ItemTemplate>
<asp:LinkButton ID="lnkEliminarImagen" runat="server" OnClick="lnkEliminarImagen_Click" CausesValidation="false"><i class="fa fa-times" ></i></asp:LinkButton>
<span>
<asp:RadioButton runat="server" ID="rbLogoSeleccionado" Text='Logo 0' GroupName="nombreLogo" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoApp" Text='Logo 1' GroupName="nombreLogoApp" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoAppBlanco" Text='Logo 2' GroupName="nombreLogoAppBlanco" />
<asp:HiddenField runat="server" ID="hdLogoId" Value='<%#Eval("id").ToString()%>' />
</span>
</ItemTemplate>
</asp:Repeater>
JS
for simulating GroupName behaviour. Avoiding to have more than one
radio button checked per row
<script>
function SetUniqueRadioButton(text, current) {
for (i = 0; i < document.forms[0].elements.length; i++) {
elm = document.forms[0].elements[i]
if ((elm.type == 'radio') && (elm.value == text)) {
elm.checked = false;
}
}
current.checked = true;
}
</script>
CS
protected void repeaterImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
RadioButton rbLogoSeleccionado = (RadioButton)e.Item.FindControl("rbLogoSeleccionado");
RadioButton rbLogoSeleccionadoApp = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoApp");
RadioButton rbLogoSeleccionadoAppBlanco = (RadioButton)e.Item.FindControl("rbLogoSeleccionadoAppBlanco");
string script = "SetUniqueRadioButton('rbLogoSeleccionado',this)";
string scriptApp = "SetUniqueRadioButton('rbLogoSeleccionadoApp',this)";
string scriptAppBlanco = "SetUniqueRadioButton('rbLogoSeleccionadoAppBlanco',this)";
rbLogoSeleccionado.Attributes.Add("onclick", script);
rbLogoSeleccionadoApp.Attributes.Add("onclick", scriptApp);
rbLogoSeleccionadoAppBlanco.Attributes.Add("onclick", scriptAppBlanco);
}
}
catch (Exception ex)
{
PIPEvo.Log.Log.RegistrarError(ex);
throw;
}
}
I tried:
Surrounding the radio buttons by LinkButton (and use Click and Command event... None is raising...). It Didnt work.
Define the ItemCommand as usual (trick CauseValidation="false" as well). It didnt work. (1)
Setting the link between linkbutton and his function event programatically (as radio button). It didnt work.
ITEMCOMMAND CODE (1)
CSHTML
<asp:Repeater runat="server" ID="repeaterImages" OnItemDataBound="repeaterImages_ItemDataBound" OnItemCommand="repeaterImages_ItemCommand">
<ItemTemplate>
<asp:LinkButton ID="lnkEliminarImagen" runat="server" OnClick="lnkEliminarImagen_Click" CausesValidation="false"><i class="fa fa-times" ></i></asp:LinkButton>
<span>
<asp:LinkButton runat="server" ID="lnkbtnbtn" OnCommand="lnkbtnbtn_Command" CommandArgument='<%#Eval("LOGO_ID").ToString()%>' CausesValidation="false" CommandName="prueba"></asp:LinkButton>
<asp:RadioButton runat="server" ID="rbLogoSeleccionado" Text='Logo 0' GroupName="nombreLogo" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoApp" Text='Logo 1' GroupName="nombreLogoApp" /><br />
<asp:RadioButton runat="server" ID="rbLogoSeleccionadoAppBlanco" Text='Logo 2' GroupName="nombreLogoAppBlanco" />
<asp:HiddenField runat="server" ID="hdLogoId" Value='<%#Eval("id").ToString()%>' />
</span>
</ItemTemplate>
</asp:Repeater>
CS
protected void repeaterImages_ItemCommand(object source, RepeaterCommandEventArgs e)
{
HiddenField id = (HiddenField)e.Item.FindControl("hdLogoId");
string idlogo = id.Value;
switch (e.CommandName)
{
case ("prueba"):
string idid = e.CommandArgument.ToString();
break;
}
}
IDEA I AM LOOKING FOR
Associate each radiobutton to its image (through id) respectively.
When I, finally, submit I could do my stuff, knowing radiobutton (action I will do) and image (logo_id) specific

Dynamically give Id to button, Commandargument send value

Here is my part of Shop.aspx code:
<% foreach(var item in items){ %>
...
<asp:Button id="btnBuy" runat="server" class="btn" Text="Buy" OnClick ="btnBuy_Click" CommandArgument='<%#Eval("item.id") %>' />
<% } %>
I've got a loop where I create few buttons to my shopping items, and I need them to have id of my item
protected void btnBuy_Click(object sender, EventArgs e)
{
int itemId = Convert.ToInt32(btnBuy.CommandArgument);
}
On click i need to have id of the item/button clicked, to save them later in my database.
Problem -
When i click on button btnbuy.CommandArgument is "".
It's wrong: you wrote c#in asp style. You have to use a Repeater and then you can manage ItemCommand for every button click.
Aspx
<asp:Repeater ID="myRepeater" runat="server" OnItemCommand="myRepeater_ItemCommand">
<ItemTemplate>
<asp:Label id="myLbl" runat="server" Text='<%# ((Item)(Container.DataItem)).ProductName %>'/>
<asp:Button id="btnBuy" runat="server" CssClass="btn" Text="Buy" CommandName="Click" CommandArgument='<%# ((Item)(Container.DataItem)).ProductId %>' />
</ItemTemplate>
</asp:Repeater>
c# (eg. OnLoad)
List<Item> myCollection = ...; // get list of items
myRepeater.DataSource = myCollection;
myRepeater.DataBind();
...
protected void myRepeater_ItemCommand(Object sender, RepeaterCommandEventArgs e)
{
if(e.CommandName == "Click")
{
int idRecord = Convert.ToInt32(e.CommandArgument);
// do something using idRecord or
// get sender properties: ((Button)e.CommandSource).Text
}
}

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;

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

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

Categories

Resources