Change value of label and hide imagebutton in asp repeater - c#

I've an asp repeater which has some fields inside an ItemTemplate. Each item in the repeater has an "add to cart" asp:ImageButton and an invisible asp:Label as well. The code looks like this:
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="addToCart">
<HeaderTemplate>
<table id="displayTable">
</HeaderTemplate>
<ItemTemplate>
<td>
<!-- fields like name, description etc in the repeater are present; i've omitted to show them here-->
<asp:Label ID="addedToCartLabel" runat="server" Visible="false"></asp:Label>
<asp:ImageButton ID="addToCartImg" runat="server" ImageUrl="hi.jpg" Width="75px" Height="50px" />
</td>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
When a particular ImageButton in the repeater is clicked, I'm trying to display "added to cart" as the text of its corresponding Label, and make the clicked ImageButton Visible=false. I've tried using the OnItemCommand function for the ASP:Repeater. The method is "addToCart":
<>
void addToCart(Object Sender, RepeaterCommandEventArgs e)
{
Cart cart = new Cart();
cart.instrument_id = //id of product from repeater based on user click
String userName = Membership.GetUser().ToString();
cart.user_name = userName;
cart.quantity = 1;
var thisLbl = (Label)e.Item.FindControl("addedToCartLabel");
var thisImg = (ImageButton)e.Item.FindControl("addToCartImg");
try
{
database.Carts.InsertOnSubmit(cart);
database.SubmitChanges();
thisImg.Visible = false;
thisLbl.Text = "Added to Cart!";
thisLbl.Visible = true;
}
catch (Exception ex)
{
thisImg.Visible = false;
thisLbl.Text = "Processing failed;please try again later";
thisLbl.Visible = true; ;
}
}
The aspx page is populated properly. However, when I click on any of the ImageButtons in the repeater, I get the following error:
Server Error in '/mysite' Application.
Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%# Page EnableEventValidation="true" %> in a page.
For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.
If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback
or callback data for validation.
Can someone help me with this?

May I suggest doing this with client-side javascript rather than a server-side call?
<asp:Label ID="addedToCartLabel" runat="server" Visible="false"></asp:Label>
<asp:ImageButton ID="addToCartImg" runat="server" ImageUrl="hi.jpg" Width="75px" Height="50px" />
becomes
<asp:Label ID="addedToCartLabel" runat="server" Visible="false"></asp:Label>
<asp:ImageButton ID="addToCartImg" runat="server" onclick="javascript:function() { this.this.style.display='none'; document.getElementById(this.parentNode.firstChild.id).style.display='block'; }" ImageUrl="hi.jpg" Width="75px" Height="50px" />

Related

Bind Gridview on Treeview Node Click

I want to bind gridview on treenode click.code works fine without error but in UI nothing changes, but when I use same code on button click, Gridview binds data properly.
My apsx code is
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div style="overflow: scroll; height: 450px;">
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:TreeView ID="Folder_Treeview" runat="server" ShowLines="true" LeafNodeStyle-CssClass="childnode"
Style="" ForeColor="Blue" SelectedNodeStyle-ForeColor="Green" OnSelectedNodeChanged="Folder_Treeview_SelectedItemChanged">
</asp:TreeView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<asp:GridView ID="GridView1" CssClass="grid" GridLines="None" ShowFooter="true" AllowPaging="true"
PageSize="5" AutoGenerateColumns="false" OnPageIndexChanging="GridView1_PageIndexChanging"
runat="server">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#Eval("Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="File Length">
<ItemTemplate>
<asp:Label ID="lblLen" runat="server" Text='<%#Eval("Length")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="File Extention">
<ItemTemplate>
<asp:Label ID="lblFileType" runat="server" Text='<%#Eval("Extension")%>'>
</asp:Label></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Creation Date & Time">
<ItemTemplate>
<asp:Label ID="lblDateTime" runat="server" Text='<%#Eval("CreationTime")%>'>
</asp:Label></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<p>
<asp:Label Text="" ID="lblMsg" runat="server"></asp:Label></p>
CS Code:
protected void Folder_Treeview_SelectedItemChanged(object sender, EventArgs e)
{
TreeNode node = this.Folder_Treeview.SelectedNode;
SetFolderPath(node);
}
public void SetFolderPath(TreeNode node)
{
Session["ParentFolderId"] = node;
// System.IO.DirectoryInfo RootDir = new System.IO.DirectoryInfo(Server.MapPath("~/"));
string CurrNode = node.Text;
string separator = "\\";
Folder_Treeview.PathSeparator = Convert.ToChar(separator);
while (node.Parent != null)
{
CurrNode = node.Parent.Text + this.Folder_Treeview.PathSeparator + CurrNode;
node = node.Parent;
}
ViewState["Folder"] = CurrNode;
ViewState["FileType"] = "All";
GetFilesFromFolder();
}
private void GetFilesFromFolder()
{
// GET A LIST OF FILES FROM A SPECIFILED FOLDER.
DirectoryInfo objDir = new DirectoryInfo(Server.MapPath((string)ViewState["Folder"]));
FileInfo[] listfiles = objDir.GetFiles("*." + ((string)ViewState["FileType"] != "All" ?
ViewState["FileType"] : "*"));
if (listfiles.Length > 0)
{
// BIND THE LIST OF FILES (IF ANY) WITH GRIDVIEW.
GridView1.Visible = true;
GridView1.DataSource = listfiles;
GridView1.DataBind();
lblMsg.Text = listfiles.Length + " files found";
}
else
{
GridView1.Visible = false;
lblMsg.Text = "No files found";
}
}
OnSelectedNodeChanged method get called on node click, and all value sets properly but never get reflect.
Please help.
It's your update panel. The node event originates within the UpdatePanel so only the Update panel will get updated after postback. Keep in mind that the full Page lifecycle occurs, so the gridview does get databound, but only the content within the UpdatePanel will be refreshed.
Your options:
Add Folder_Treeview as a PostBack Trigger -or-
Get rid of the UpdatePanel altogether -or-
Move the Gridview inside the UpdatePanel ContentTemplate
Also a TreeView is one of several server controls that may not be compatible with an UpdatePanel:
The following ASP.NET controls are not compatible with partial-page updates, and are therefore not designed to work inside an UpdatePanel control:
TreeView control under several conditions. One is when callbacks are enabled that are not part of an asynchronous postback. Another is when you set styles directly as control properties instead of implicitly styling the control by using a reference to CSS styles. Another is when the EnableClientScript property is false (the default is true). Another is if you change the value of the EnableClientScript property between asynchronous postbacks. For more information, see TreeView Web Server Control Overview.
Menu control when you set styles directly as control properties instead of implicitly styling the control by using a reference to CSS styles. For more information, see Menu Control Overview.
FileUpload and HtmlInputFile controls when they are used to upload files as part of an asynchronous postback.
GridView and DetailsView controls when their EnableSortingAndPagingCallbacks property is set to true. The default is false.
Login, PasswordRecovery, ChangePassword, and CreateUserWizard controls whose contents have not been converted to editable templates.
The Substitution control.

Handling click event without postback

I have a listview that populates with data. This listview is inside a user control which sits inside a page called Preferences.aspx. Today I am handling click event on each row meaning that involves posting back to server.
Now, I have to put another user control on Preferences.aspx because there are group of more settings which need to be presented separately to users. I have added the new user control inside a separate tab on the page. This new tab has to be the first one to show when user lands on Preferences.aspx.
Now the problem is that when user goes to second tab (user control with listview) and click on a row, a postback occurs. This puts the user on the first tab (newly added user control).
So I wonder how can I get click event on a row without having to postback?
Any ideas or suggestions are welcome.I am working in Asp.Net with C#.
The code is:
Markup inside the user control:
<asp:TableRow runat="server" id="trVisitor" CssClass='<%# GetRowClass() %>' >
<asp:TableCell ID="tdPicture" runat="server" Width="10" onclick='<%# GetClickPostBack(Container.ItemIndex) %>'>
<div style="margin-top:1px;">
<asp:Image ImageUrl=' <%# Page.ResolveUrl("~/" + Eval("Visitor.StatusImageUrl")) %>' visible='<%# historyFlag ? false : true %>' runat="server"/>
</div>
</asp:TableCell>
... and so on
Markup inside Preferences.aspx:
<ABC:ListControl runat="server" ID="visitorListControl" CanSelect="true" IsMine="true" Recurring="false" OnVisitorSelected="ListControl_VisitorSelected" />
And code behind is:
protected string GetClickPostBack(int itemIndex)
{
if (CanSelect)
//return 0.ToString();
return "javascript: " + Page.ClientScript.GetPostBackEventReference(this, VisitorRowPrefix + itemIndex) + "; return false;";
else
return string.Empty;
}
public void RaisePostBackEvent(string eventArgument)
{
if (eventArgument.StartsWith(VisitorRowPrefix))
{
HandleRowClick(Convert.ToInt32(eventArgument.Substring(VisitorRowPrefix.Length)));
}
}
private void HandleRowClick(int index)
{
int CmgVisitorId = Constants.NotConfigured;
// bool IsHistoricVisitor = false;
// Visitor HistoricVisitor = new Visitor();
// Mark only the clicked row
... and so on.
Hook up to the grid button's click event using JavaScript/jQuery, and prevent theirs default behaviour (post-back) by 2 possible means:
return false;
e.preventDefault (jQuery only)
Example (using jQuery):
$('.button').click(function(event){
event.preventDefault();
//Write your client-side logic here
});
Description: If this method is called, the default action of the event
will not be triggered.
If I am understanding the issue properly, try an update panel.
Check out the documentation here.
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:TableRow runat="server" id="trVisitor" CssClass='<%# GetRowClass() %>' >
<asp:TableCell ID="tdPicture" runat="server" Width="10" onclick='<%# GetClickPostBack(Container.ItemIndex) %>'>
<div style="margin-top:1px;">
<asp:Image ImageUrl=' <%# Page.ResolveUrl("~/" + Eval("Visitor.StatusImageUrl")) %>' visible='<%# historyFlag ? false : true %>' runat="server"/>
</div>
</asp:TableCell>
</ContentTemplate>
</asp:UpdatePanel>

Change Css class on a Panel thats located inside a Asp:repeater

Hello and thanks for taking your time to read this.
I'm trying to change the CSS class of a panel thats located inside a Repeater when I select a RadioButton.
<div>
<asp:RadioButtonList OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged" AutoPostBack="true" ID="RadioButtonList1" RepeatDirection="Horizontal" runat="server">
<asp:ListItem Selected="True">Show Gallery</asp:ListItem>
<asp:ListItem>Show List</asp:ListItem>
</asp:RadioButtonList>
</div>
<div class="RpOutterFrame" runat="server" id="RpOutterFrame">
<asp:Repeater runat="server" ID="RP">
<ItemTemplate>
<panel class="ShowDiv" runat="server" id="RpInnerFrame">
<img runat="server" style="width: 80px;" id="ModelImg" class="ModelImg" src='<%# string.Format("~/Content/Img/ModelImg/{0}", Eval("Image")) %>' />
<br />
<%# Eval("Model") %>
</panel>
</ItemTemplate>
</asp:Repeater>
</div>
My C#:
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (RadioButtonList1.Items[0].Selected == true)
{
RpOutterFrame.Attributes["class"] = "RpOutterFrame";
Panel panel = (Panel)this.FindControl("RpInnerFrame");
panel.CssClass = "ShowDiv2";
}
}
As you can see the Panel already has the class ShowDiv and then I would like it to change the class to ShowDiv2 when I select/click the Radiobutton.
Anyone who can help me figuar what I'm doing wrong or fix the code?
A Repeater's purpose is to repeat something. So normally it contains multiple elements. Therefore the RepeaterItem is the NamingContainer which must contain unqiue ID's and where you can find your controls via FindControl(ID).
So this does not work since this is the Page which is not the NamingContainer of the Panel:
Panel panel = (Panel)this.FindControl("RpInnerFrame");
panel.CssClass = "ShowDiv2";
You have to loop all items:
foreach(RepeaterItem item in RP.Items)
{
Panel panel = (Panel)item.FindControl("RpInnerFrame");
panel.CssClass = "ShowDiv2";
}
Apart from that you should use the ASP:Panel instead of Panel.
So change
<panel class="ShowDiv" runat="server" id="RpInnerFrame">
// ...
</panel>
to
<ASP:Panel CssClass="ShowDiv" runat="server" id="RpInnerFrame">
// ...
</ASP:Panel>

RadComboBox pre selection

First of all what I want to do is to pre select a value in my RadComboBox ,and if this value is not selected something else is selected then change the visibility to of some specific fields hidden.
My problem is that I'm able to make my pre select but somehow I can not change the status of my visibility for my specific fields when this pre selected value has changed.
What I have tired is to do it with a standard event OnSelectedIndexChanged but some how this is not triggering why so ever.. I have also added AutoPostBack=true as well as ViewStateMode=Enabled"
First my field's
Here comes my preslect as well here I would like to trigger the visibility change
<div class="formRowDiv">
<asp:Label ID="Activitylbl" runat="server" Text="Activity" CssClass="formLabel" />
<telerik:RadComboBox ID="rcbActivity" CssClass="rowForm" ViewStateMode="Enabled" runat="server" Width="260px" EmptyMessage="- Activity -"
DataTextField="ActivityId" DataValueField="ActivityId" AutoPostBack="true" OnSelectedIndexChanged="rcbActivity_SelectedIndexChanged">
</telerik:RadComboBox>
<asp:RequiredFieldValidator runat="server" Display="Dynamic" ControlToValidate="rcbActivity"
ErrorMessage="Can not be empty" CssClass="rowFormValidation" />
</div>
What I want to hide:
<div class="formRowDiv">
<asp:Label ID="ActivityDescription" runat="server" Text="ActivityDescription" CssClass="formLabel" Visible="false"/>
<telerik:RadTextBox runat="server" ID="rtbActivityDescription" Wrap="true" Height="50" TextMode="MultiLine" AutoPostBack="true" CssClass="rowForm" ReadOnly="true" Visible="false" />
</div>
How I do my pre selection :
In my databind method that is called in my Page_Load
I firrst loop and then do a pre select
foreach (Activity item in ctx.Activity.OrderBy(l =>l.Code))
{
rcbActivity.Items.Add(new RadComboBoxItem(item.FullActivity, item.ActivityId.ToString()));
if (rcbActivity.Items.FindItemByValue("4") != null)
{
rcbActivity.SelectedIndex = rcbActivity.Items.IndexOf(rcbActivity.Items.FindItemByValue("4"));
ActivityDescription.Visible = true;
rtbActivityDescription.Visible = true;
rtbActivityDescription.ReadOnly = false;
}
}
Here is how I would hide my Fields
protected void rcbActivity_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
ActivityDescription.Visible = true;
rtbActivityDescription.Visible = true;
rtbActivityDescription.ReadOnly = false;
}
In case your controls are in an update panel then try removing it if the update panel is not so important and see if the changes u make to the controls in the server side are getting affected properly

Need help with making label of repeater visible and link button hidden in code behind

aspx page:-
<asp:Repeater ID="rptAdd" OnItemCommand="rptAdd_ItemCommand" runat="server">
<ItemTemplate>
<td>
<asp:LinkButton ID="lnkBill" Text="Make Default" runat="server" Visible="true" CommandName="DefaultBill"></asp:LinkButton>
<asp:Label ID="labelBill" Text="Yes" Visible="false" runat="server"></asp:Label>
</td>
</ItemTemplate>
</asp:Repeater>
Code Behind:-
protected void rptAdd_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "DefaultBill")
{
Users objBill = new Users();
objBill.IsDefault = true;
e.Item.FindControl("labelBill").Visible=true;
e.Item.FindControl("lnkBill").Visible = false;
}
}
In code behind intellisense is not detecting "labelBill" and "lnkBill"..what could be wrong ?
Also need to know...that's how u access controls in a repeater ?? like using findControl() ...right ?
[EDIT]
Changed code as follows..still not working...
((Label)e.Item.FindControl("labelBill")).Visible=true;
((LinkButton)e.Item.FindControl("lnkBill")).Visible = false;
Why wont intellisense detect these two IDs??
The problem is that your controls are inside a repeater, the find control wont search recursively. Try this instead.
rptAdd.FindControl("labelBull").Visible = true;

Categories

Resources