<asp:Repeater ID="Cartridges" runat="server" onitemcommand="Cartridges_ItemCommand">
<ItemTemplate>
<p class="cartprice"><%#String.Format("{0:C}", Eval("Price"))%></p>
<hr class="hr4" />
<p class="cartqty">QTY <asp:TextBox ID="cartQty" Text="0" runat="server"></asp:TextBox> </p>
<div class="cartbuy2"><asp:LinkButton ID="buy" runat="server" CommandName="AddtoCart" CommandArgument=<%#Eval("cartID") %> Text="Buy"></asp:LinkButton></div>
</ItemTemplate>
</asp:Repeater>
How can I pass the textbox value within CommandArgument? Sorry totally lost...
Did you try: CommandArgument='<%#Eval("cartID") %>'
this is different from yours as it is surrounded by a single quote, I guess this is the correct syntax.
Use FindControl to get other items in the repeater Item. For Example:
protected void repeater_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
LinkButton lb = (LinkButton)e.CommandSource;
string textBoxValue = ((TextBox)lb.Parent.FindControl("cartQty")).Text;
}
you need to bind the cartId to the linkbutton onItemDataBound and then access it onItemCommand, I have modified code for you, give this a go
<asp:Repeater ID="Cartridges" runat="server" onitemcommand="Repeater_OnItemCommand" OnItemDataBound="Repeater_OnItemDataBound">
<ItemTemplate>
<p class="cartprice"><%#String.Format("{0:C}", Eval("Price"))%></p>
<hr class="hr4" />
<p class="cartqty">QTY <asp:TextBox ID="cartQty" Text="0" runat="server"></asp:TextBox> </p>
<div class="cartbuy2"><asp:LinkButton ID="buy" runat="server" CommandName="AddtoCart" Text="Buy"></asp:LinkButton></div>
your onItemdatabound should look like this
protected void Repeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
//your code...
LinkButton add = (LinkButton)e.Item.FindControl("buy");
add.CommandArgument = cartID.ToString();
}
and then you can access the text box on item command like this
protected void Repeater_OnItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "AddtoCart")
{
LinkButton btnEdit = (LinkButton)e.CommandSource;
if (btnEdit != null)
{
string editId = btnEdit.CommandArgument;
string text = ((TextBox)e.Item.FindControl("cartQty")).Text;
//do some stuff with your cartid and quantity
}
}
}
You can also extend your code with edit/delete command arguments by adding more linkbuttons and binding them to the correct command and then accessing them in on item command
Thanks
Related
I have a repeater inner another repeater and this second one i have a list of checkbox and i need to get the value of the checked.
This is my front code:
<asp:Repeater runat="server" ID="rptPerfis" OnItemDataBound="ItemBound">
<ItemTemplate>
<div class="mws-form-row">
<ul class="mws-form-list inline" style="float: none; display: inline;">
<li style="padding-top: 10px;">
<%# rptNome(Container) %></li>
</ul>
<asp:Repeater runat="server" ID="rptUsers">
<ItemTemplate>
<div class="mws-form-item radioPermissoes clearfix" style="float: none;">
<ul class="mws-form-list inline">
<li>
<asp:CheckBox runat="server" Text="<%# rptAdministradorNome(Container) %>" ID="checkUser" CssClass="<%# rptAdministradorPostClass(Container) %>" /></li>
</ul>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<br />
<hr />
</ItemTemplate>
</asp:Repeater>
<asp:LinkButton runat="server" ID="fLnkSalvar" class="mws-ic-16 ic-disk" OnClick="fLnkSalvar_Click">Salvar</asp:LinkButton>
and this is how i fill this repeater:
protected void Page_Load(object sender, EventArgs e)
{
listaAdm = Servicos.AdministradorMySql.ListarEmpresa(denuncia.Empresa).OrderByDescending(x => x.Nome).ToList();
todosPerfis = Servicos.Perfil.ListarTodos().ToList();
rptPerfis.DataSource = todosPerfis.Where(x => x.Ativo).OrderBy(x => x.Nome);
rptPerfis.DataBind();
}
protected void ItemBound(object sender, RepeaterItemEventArgs args)
{
if (args.Item.ItemType == ListItemType.Item || args.Item.ItemType == ListItemType.AlternatingItem)
{
int idPerfil = ((Perfil)args.Item.DataItem).ID;
Repeater childRepeater = (Repeater)args.Item.FindControl("rptUsers");
childRepeater.DataSource = listaAdm.Where(x => x.Perfil > 1 && x.Perfil == idPerfil).ToList();
childRepeater.DataBind();
}
}
protected void fLnkSalvar_Click(object sender, EventArgs e)
{
Administrador usuario = new Administrador();
usuario.Permissoes = new List<string>();
// i need to get this values here to fill this `List<string>` and then save
foreach (var x in usuario.Permissoes)
{
Servicos.Denuncia.InserirUsuarios(denuncia.ID, x);
}
}
I've no idea how can i get this values or if there another easier way without add in the list i think its better
You have to use FindControl on multiple levels. First the correct Item in the parent Repeater, then find the CheckBox in the correct Item of the child Repeater.
var cb = ((Repeater)rptPerfis.Items[i].FindControl("rptUsers")).Items[j].FindControl("checkUser") as CheckBox;
PS you need to wrap the code in Page_Load in an IsPostBack check or you will never retrieve the correct checkbox state in a PostBack.
Comments DataList (Outer) and Replies DataList (Inner).
While in Inner DataList there is a LinkButton that gets text from TextBox.
How I can access Add event of that LinkButton?
.aspx code
<asp:DataList ID="dlComments" runat="server">
<asp:DataList ID="dlReplies" runat="server">
<asp:TextBox ID="txtReply" TextMode="MultiLine" Rows="3" Width="100%" runat="server"></asp:TextBox>
<asp:LinkButton ID="lbEdit" CommandName="Add" runat="server">Edit</asp:LinkButton>
</asp:DataList>
</asp:DataList>
You can add the OnItemCommand to the nested DataList.
<asp:DataList ID="dlReplies" runat="server" OnItemCommand="dlReplies_ItemCommand">
And then in code behind
protected void dlReplies_ItemCommand(object source, DataListCommandEventArgs e)
{
//check for the correct commandname
if (e.CommandName == "Add")
{
//use findcontrol to find the textbox and cast it back to one
TextBox tb = e.Item.FindControl("txtReply") as TextBox;
Label1.Text = tb.Text;
}
}
Add commandName="click" on you linkbutton.
private void DataList1_ItemCreated(object sender, System.Web.UI.WebControls.DataListItemEventArgs e) {
if ((e.Item.ItemType == ListItemType.AlternatingItem)
|| (e.Item.ItemType == ListItemType.Item)) {
DataList dtl2 = (DataList)(e.Item.FindControl("dlReplies"));
dtl2.ItemCommand += new System.EventHandler(this.dtl2_ItemCommand);
}
}
protected void dtl2_ItemCommand(object sender, System.Web.UI.WebControls.DataListCommandEventArgs e) {
if (e.CommandName == "click") {
// 'do what you want here
}
}
I have a repeater and have some labels and a button inside it. Here is my .aspx:
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="EntityDataSourceTeklifler" OnItemCommand="Repeater1_ItemCommand" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
<div class="panel panel-primary">
<div class="panel-body">
<strong>Teklif No.</strong> <asp:Label ID="lblTeklifNo" runat="server" Text='<%#Eval("TeklifId") %>'></asp:Label><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" CommandArgument='<%# Eval("TeklifId") %>' />
</div>
</div>
</ItemTemplate>
</asp:Repeater>
And my codebehind:
protected string CheckIfApproved(bool isApproved)
{
string result;
if (isApproved)
{
result = "Satışa Dönmüştür";
}
else
{
result = "Satışa Dönmemiştir";
}
return result;
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
string teklifId = e.CommandArgument.ToString();
TeklifTable teklif = entity.TeklifTable.Where(t => t.TeklifId == teklifId).FirstOrDefault();
teklif.Approved = true;
entity.SaveChanges();
Page_Load(null, EventArgs.Empty);
}
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;
}
else
{
lbl.ForeColor = System.Drawing.Color.Purple;
}
}
}
As you can see my repeater changes label color and button visibility according to boolean attribute 'Approved' of my database. Approved attribute changes with the button click and there isn't any problem here. I am checking approved value if it is true or false and changes label according to it. Lastly ItemDataBound method changes label color and button visibility according to label which has been changed in checkIfApproved method.
Now, here is my problem. As you can see I defined default label color as red in .aspx. This should changed to blue or purple but SOME OF THE VALUES stays as red. That means 'Repeater1_ItemDataBound' method does not effect some of the values. Here is another interesting point: First item of repeater get effected as I want and displayed as blue or purple according to label text but second item comes red.That means second item does not get effected by this method. Third item get effected and fourth does not. This goes like this. Any ideas ?
The probelm with your code is that you are only checking if the item is a Item type but repeater control item consists of Item as well as AlternatingItem i.e. every alternating item acts falls under AlternatingItem of ListItemType.
Simply add this line in your ItemDataBound event:-
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
//your code here
}
}
I have a ListView control with DataPager, i am trying to show results from database into ListView the database have field in which i have store content from ajaxhtmlextender i have bind ListView with database like this
protected void ListEvents()
{
conn = new SqlConnection(connSting);
cmdListEvent = new SqlCommand("SELECT * FROM LatestEvents",conn);
table = new DataTable();
conn.Open();
adpter = new SqlDataAdapter(cmdListEvent);
adpter.Fill(table);
ListEvent.DataSource = table;
ListEvent.DataBind();
conn.Close();
}
and the .aspx file
<asp:ListView ID="ListEvent" runat="server"
OnItemDataBound="ListEvent_ItemDataBound" >
<LayoutTemplate>
<asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
</LayoutTemplate>
<ItemTemplate>
<div class="contmainhead">
<h1 id="evhead"><asp:Label ID="LabelTittle" runat="server"><%#Eval("Tittle") %></asp:Label></h1>
</div>
<div class="contmain">
<asp:Label ID="LabelBody" runat="server"> <%#Eval("Body") %></asp:Label>
</div>
</ItemTemplate>
</asp:ListView>
It is giving the intended results but the problem is the label
<asp:Label ID="LabelBody" runat="server"> <%#Eval("Body") %></asp:Label>
showing all the formatted text and images as html markup, i know to work the label perfectly i have to use this function
Server.HtmlDecode();
i tried it like this
protected void ListEvent_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
Label LabelBody = (Label)e.Item.FindControl("LabelBody");
LabelBody.Text = Server.HtmlDecode(LabelBody.Text);
}
}
But the label shows nothing. . so how can i make the label show the content correctly?
Your help will be greatly appreciated . .Thanx
protected void ListEvent_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
ListViewDataItem dataItem = (ListViewDataItem) e.Item;
Label LabelBody = (Label)e.Item.FindControl("LabelBody");
LabelBody.Text = (string) DataBinder.Eval(dataItem.DataItem, "Body");
}
}
Please make sure there is a column named in your returned datatable
and also remove the <%# EVAL %> tag from the text attribute of your label, leave it empty or do not specify the attribute in your aspx
try
<asp:Label ID="LabelBody" runat="server" text='<%#Eval("Body") %>' />
EDIT :
if the above didn't work try :
<asp:Label ID="LabelBody" runat="server" text="<% #Eval("Body").ToString() %>" />
I have a repeater and each item contains a button which should redirect to another page and also pass a value in the query string.
I am not getting any errors, but when I click the button, the page just refreshes (so I am assuming a postback does occur) and does not redirect. I think that for some reason, it isn't recognizing the CommandName of the button.
Repeater code:
<asp:Repeater ID="MySponsoredChildrenList" runat="server" OnItemDataBound="MySponsoredChildrenList_ItemDataBound" OnItemCommand="MySponsoredChildrenList_ItemCommand">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<br />
<div id="OuterDiv">
<div id="InnerLeft">
<asp:Image ID="ProfilePic" runat="server" ImageUrl='<%#"~/Resources/Children Images/" + String.Format("{0}", Eval("Primary_Image")) %>'
Width='300px' Style="max-height: 500px" /></div>
<div id="InnerRight">
<asp:HiddenField ID="ChildID" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "Child_ID") %>'/>
<span style="font-size: 20px; font-weight:bold;"><%# DataBinder.Eval(Container.DataItem, "Name") %>
<%# DataBinder.Eval(Container.DataItem, "Surname") %></span>
<br /><br /><br />
What have you been up to?
<br /><br />
<span style="font-style:italic">"<%# DataBinder.Eval(Container.DataItem, "MostRecentUpdate")%>"</span>
<span style="font-weight:bold"> -<%# DataBinder.Eval(Container.DataItem, "Update_Date", "{0:dd/MM/yyyy}")%></span><br /><br /><br />Sponsored till:
<%# DataBinder.Eval(Container.DataItem, "End_Date", "{0:dd/MM/yyyy}")%>
<br /><br />
<asp:Button ID="ChildProfileButton" runat="server" Text="View Profile" CommandName="ViewProfile" />
</div>
</div>
<br />
</ItemTemplate>
<SeparatorTemplate>
<div id="SeparatorDiv">
</div>
</SeparatorTemplate>
</asp:Repeater>
C# Code behind:
protected void MySponsoredChildrenList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
// Stuff to databind
Button myButton = (Button)e.Item.FindControl("ChildProfileButton");
myButton.CommandName = "ViewProfile"; }
}
protected void MySponsoredChildrenList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "ViewProfile")
{
int ChildIDQuery = Convert.ToInt32(e.Item.FindControl("ChildID"));
Response.Redirect("~/ChildDescription.aspx?ID=" + ChildIDQuery);
}
}
I am new to using repeaters so it's probably just a rookie mistake. On a side note: is there a better way of obtaining the ChildID without using a hidden field?
EDIT: Using breakpoints; the ItemDatabound event handler is being hit, but the ItemCommand is not being entered at all
You need to set MySponsoredChildrenList_ItemDataBound as protected. Right now, you have just 'void' which by default is private, and is not accessible to the front aspx page.
Another way is to use the add event handler syntax from a function in your code behind, using the += operator.
Either way, the breakpoint will now be hit and our code should mwork.
EDIT: So the above solved the compilation error but the breakpoints are not being hit; I've ran some tests and am able to hit breakpoints like this:
Since I do not know how you are databinding, I just added this code to my code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MySponsoredChildrenList.DataSource = new List<object>() { null };
MySponsoredChildrenList.DataBind();
}
}
Note: If you DataBind() and ItemDataBound() is called on every postback, it will wipe out the command argument, which is potentially what you are seeeing; so if you always see [object]_ItemDataBound() breakpoint hit, but never [object]_ItemCommand(), it is because you need to databind only on the initial page load, or after any major changes are made.
Note also the method MySponsoredChildrenList_ItemCommand doesn't work:
protected void MySponsoredChildrenList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "ViewProfile")
{
int ChildIDQuery = Convert.ToInt32(e.Item.FindControl("ChildID"));
Response.Redirect("~/ChildDescription.aspx?ID=" + ChildIDQuery);
}
}
When you do FindControl, you need to cast to the correct control type, and also make sure to check for empty and null values before converting, or else you will possibly have errors:
protected void MySponsoredChildrenList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "ViewProfile")
{
int childId = 0;
var hiddenField = e.Item.FindControl("ChildID") as HiddenField;
if (null != hiddenField)
{
if (!string.IsNullOrEmpty(hiddenField.Value))
{
childId = Convert.ToInt32(hiddenField.Value);
}
}
if (childId > 0)
{
Response.Redirect("~/ChildDescription.aspx?ID=" + childId);
}
}
}
Hope this helps - if not, please post additional code for the "full picture" of what is happening, so we can see where else you might have a problem.
I think on the repeater you need to add
OnItemDataBound="MySponsoredChildrenList_ItemDataBound"
Not 100% sure, but could be the same for the ItemCommand.
--
In regards to obtaining the ChildID. Add a CommandArgument to the button in the repeater, and set it in the same way, <% Eval("ChildID") %>. This can the be obtained using e.CommandArgument.
Try this.. Add an attribute to item row
row.Attributes["onclick"] = string.Format("window.location = '{0}';", ResolveClientUrl(string.Format("~/YourPage.aspx?userId={0}", e.Item.DataItem)) );
or You can do like this also
<ItemTemplate> <tr onmouseover="window.document.title = '<%# Eval("userId", "Click to navigate onto user {0} details page.") %>'" onclick='window.location = "<%# ResolveClientUrl( "~/YourPage.aspx?userId=" + Eval("userid") ) %>"'> <td> <%# Eval("UserId") %> </td> </tr> </ItemTemplate>