I have two repeaters that looks like this :
Arrange By: Name | Age | Area
what I want to do now is to populate the second repeater from the database with the alphabet, and if the age was clicked then the second repeater gets populated from the database with some age ranges!
I already implemented my idea by placing a hyperlink in the first repeater, that passes -using it's NavigateUrl property- a url for the same page but with some querystring values!
I've been told that querystrings are used for passing values from one page to another, not the same page...and also I wanted to use some AJAX (script manager and update panel) but turns out that I have to use some server control within my repeater instead of html controls so it could be able to post back to the server
I hope you'd help me with a good implementation for passing the value from repeater1 to repeater2 and if you think that I've stated anything wrong Please Corret Me!
Thanks in advance :)
EDIT
my.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string commandString1 = "SELECT [arrange_by_id], [arrange_by] FROM [arrange_by]";
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString))
{
using (SqlCommand cm = new SqlCommand(commandString1, cn))
{
cn.Open();
using (SqlDataReader dr = cm.ExecuteReader())
{
ArrangeBy_rpt.DataSource = dr;
ArrangeBy_rpt.DataBind();
}
}
}
}
void arrange_lnkbtn_command(object sender, CommandEventArgs e)
{
Label1.Text = (e.CommandArgument).ToString();
}
my.aspx
<asp:Repeater ID="ArrangeBy_rpt" runat="server">
<ItemTemplate>
<asp:LinkButton id="arrange_lnkbtn" OnCommand="arrange_lnkbtn_command" CommandArgument='<%#Eval("arrange_by_id") %>' runat="server">
<%# Eval("arrange_by") %>
</asp:LinkButton>
</ItemTemplate>
<SeparatorTemplate> | </SeparatorTemplate>
</asp:Repeater>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
Compilation Error
Compiler Error Message: CS1061: 'ASP.sortingcontrol_ascx' does not contain a definition for 'arrange_lnkbtn_command' and no extension method 'arrange_lnkbtn_command' accepting a first argument of type 'ASP.sortingcontrol_ascx' could be found (are you missing a using directive or an assembly reference?)
Line 4: <asp:Repeater ID="ArrangeBy_rpt" runat="server">
Line 5: <ItemTemplate>
Line 6: <asp:LinkButton id="arrange_lnkbtn" OnCommand="arrange_lnkbtn_command" CommandArgument='<%#Eval("arrange_by_id") %>' runat="server">
Line 7: <%# Eval("arrange_by") %>
Line 8: </asp:LinkButton>
There's nothing wrong per se with passing data to the same page using the querystring, though it shouldn't be used for sensitive data that the user might change by "hacking" the URL. However, it's not the standard way of doing things in ASP.NET WebForms, since it won't postback the values of any other controls on the page (and hence they won't retain their state without you manually having to re-populate them on every page load). But if this is not a problem for you, feel free to stick with querystring.
Howecer, generally you would use a server-side control like an asp:Button or an asp:LinkButton and then handle their OnClick event. However, to pass data with one you can use the CommandName and CommandArgument properties of the button and then handle the OnCommand event.
<asp:LinkButton id="LinkButton1"
Text="Click Me"
CommandName="Age"
CommandArgument="18"
OnCommand="LinkButton_Command"
runat="server"/>
In code-behind:
void LinkButton_Command(Object sender, CommandEventArgs e)
{
var data = GetData(e.commandArgument); // implement a method that gets your data filtered by the argument passed from the button
Repeater2.DataSource = data;
Repeater2.DataBind();
}
Related
I have a repeater for Frequently asked questions on a Website that I'm trying to get separated into categories depending on which treeid it is related to.
When I reference the repeater (rp_FAQ) in the code behind to check if it is null so I can pass the category id to the stored procedure it keeps returning null when I need the item to exist when check that it's null.
I can't seem to find the route of the problem so as second set of eyes would be really grateful.
Thanks.
I have this repeater:
<asp:Repeater ID="rp_FAQ" DataSourceID="DS_GetFAQs" runat="server" OnItemDataBound="rp_FAQCategories_ItemDataBound">
<HeaderTemplate>
<div class="container-full fares_container">
<div class="row">
</HeaderTemplate>
<ItemTemplate>
<dt>Q: <%# Eval("Question") %></dt>
<dd>A: <%# Eval("Answer") %></dd>
</ItemTemplate>
<FooterTemplate>
</dl>
</div>
</div>
</FooterTemplate>
</asp:Repeater>
Here is my code behind:
protected void rp_FAQCategories_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Repeater rp_FAQRep = e.Item.FindControl("rp_FAQ") as Repeater;
if (rp_FAQRep != null)
{
if (TreeData.CurrentDefault.IsRelation(Convert.ToInt32(Resources.Pages.FAQ)))
{
DS_GetFAQs.SelectParameters["CategoryID"].DefaultValue = "1";
}
rp_FAQRep.DataSource = DS_GetFAQs;
rp_FAQRep.DataBind();
}
}
The FindControl method is only needed if you are trying to get a reference to a control which is inside the control which raised the event (in this case ItemDataBound). So you can either reference the control directly if it's not nested inside another control or use sender. For example:
var rp_FAQRep = rp_FAQ; //A bit pointless but demonstrates the point
or
var rp_FAQRep = (Repeater)sender;
The problem is that you are trying to find the rp_FAQ control in a control inside rp_FAQ itself.
Since e.Item is the RepeatItem under rp_FAQ, you can just cast e.Item.Parent, or sender if you will.
e.Item is the RepeaterItem within the Repeater - it does not contain the Repeater itself. Just cast the sender of the event:
var rp_FAQRep = (Repeater)sender;
I have a button inside a listview and a label. The label is bound to my database and displays a score. If you press the button I want the score to update on client side. But Since I cant access items in Listview from codebehind I have no idea how to do this. And updatepanel does not work.
My listview bound to a Sqldatasource:
<asp:ListView ID="ListViewSearch" runat="server" DataSourceID="SqlDataSourceWebsite" DataKeyNames="WebsiteID">
My buttons and my label for rating:
<asp:LinkButton ID="BtnUp" runat="server" CssClass="btn btn-default btn-xs" CommandArgument='<%# Eval("testId").ToString() %>' OnClick="up_click"></asp:LinkButton>
<asp:LinkButton ID="BtnDown" runat="server" CssClass="btn btn-default btn-xs" CommandArgument='<%# Eval("testId").ToString() %>' OnCommand="down_click"></asp:LinkButton>
<asp:Label ID="LabelRating" runat="server" Text=' <%# Eval("rating") %>'></asp:Label>
upClick() function:
protected void up_click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
String webID = btn.CommandArgument.ToString();
int ID = Convert.ToInt32(webID);
click(ID, 1);
}
Click() function:
public void click(int webID, int vote)
{
using (SqlConnection con = new SqlConnection(strCon))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "UPDATE [Test] SET [rating]+=#vote WHERE [testId]=#testID";
cmd.Parameters.AddWithValue("#webID", webID);
cmd.Parameters.AddWithValue("#vote", vote);
con.Open();
cmd.ExecuteNonQuery();
}
con.Close();
}
}
The code updates the rating as it is supposed to, but to see the change I have to refresh the page. So the questions is; How do I update a value inside a listview by clicking a button inside that same lisview?
(If this is not possible, please suggest a different way that I can display results from a search in a list that offers the same customization.)
I'm more into ASP MVC however maybe my tip will help you.
The way I did these behaviors was to bind javascript function to the button and using jQuery I've send 'GET' request to the specific action(method) on the server for example: www.myexample.com/getData?tableid=24 which responds with json containing needed data.
Hope this will direct you to proper solution.
Cheers,
Marek
I am trying to display images in eval repeater but it doesn't work. When I put simply div instead of asp:Repeater I get the image path. (I have no problem with SQL side)
Can anyone tell what's wrong with this code?
Thanks.
<div class="wrapper">
<asp:Repeater runat="server" ID="Repeater1">
<ItemTemplate>
<asp:Image ID="Image1" ImageUrl="<%# Eval("PresidentPhotoPath") %>" runat="server" />
</ItemTemplate>
</asp:Repeater>
</div>
SqlConnection cnn = new SqlConnection("Initial Catalog=whitehouse;Data Source=localhost;Integrated Security=SSPI;");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT PresidentPhotoPath FROM presidents", cnn);
SqlDataReader dr = cmd.ExecuteReader();
Repeater1.DataSource = dr;
Repeater1.DataBind();
cnn.Close();
}
}
The ImageUrl syntax here is wrong:
ImageUrl="<%# Eval("PresidentPhotoPath") %> "
You have double quotes inside of double quotes, change the outer quotes to be single quotes, like this:
ImageUrl='<%# Eval("PresidentPhotoPath") %>'
As for your issue with prepending Images/ before the file name, I would recommend using a code-behind method to build the string for you, like this:
protected string BuildPath(string photoPath)
{
return "Images/ + photoPath;
}
Note: Consider naming this something more useful than BuildPath as that is fairly generic, just picked that name because nothing better came to mind immediately.
Now in your markup you can just call the method, like this:
ImageUrl='<%# BuildPath(Eval("PresidentPhotoPath")) %>'
I recommend this approach for the following reasons:
The markup does not contain any complex logic whatsoever, just a method call with the Eval() value
It is easier to debug the logic versus embedded code blocks
You can leverage the power of Visual Studio compiler to catch syntax errors at compile-time versus run-time errors when the logic is embedded into the binding syntax of the markup
I want to use Session variable's value on the markup. This is the code written on UserContorl.ascx, file on NavigateUrl I want to send the Username which is stored in the session variable. I don't want to set NavigateUrl value on PageLoad function for some reason.
Note the code gives the error: The server tag is not well formed.
<asp:Panel ID="pnlMenuItems" runat="server" HorizontalAlign="Left">
<asp:HyperLink ID="LinkLogout" runat="server" NavigateUrl="~/logout/"+
<%= HttpContext.Current.Session["UserName"].ToString(); %>> CssClass="pnlMenuItems"
ForeColor="#666666">Logout</asp:HyperLink>
</asp:Panel>
You can bind data within server tags. e.g.
<asp:HyperLink ID="LinkLogout" runat="server"
NavigateUrl="<%# LogoutUrl %>"
CssClass="pnlMenuItems"
ForeColor="#666666">Logout</asp:HyperLink>
then in your code behind:
protected string LogoutUrl {
get {
return "~/logout/" + HttpContext.Current.Session["UserName"].ToString();
}
}
protected void Page_Load(object sender, EventArgs e) {
if(!IsPostBack) { DataBind(); }
}
The NavigateUrl gets set during the call to DataBind() using this method. In my example, the value would get set during page load, but you wouldn't have to specifically do it. If you need it to happen at a different time during the page lifecycle, you can try calling DataBind() during a different event.
How about:
<asp:Panel ID="pnlMenuItems" runat="server" HorizontalAlign="Left">
<asp:HyperLink ID="LinkLogout" runat="server"
NavigateUrl="<%# "~/logout/" + HttpContext.Current.Session["UserName"].ToString() %>"
CssClass="pnlMenuItems"
ForeColor="#666666">Logout</asp:HyperLink>
</asp:Panel>
Im using a repeater to display some products in an online shop for a school project. This is how the front end looks with the repeater
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="rptList_ItemCommand">
<ItemTemplate>
<span style="float:left; padding:25px;" class="backgrnd">
<asp:ImageButton ID="imgProd" runat="server" style="width:150px; height:150px;" ImageUrl='<%# DataBinder.Eval(Container.DataItem, "productImg")%>' CommandArgument='<%# DataBinder.Eval(Container.DataItem, "productID")%>' CommandName="ViewIndividProd"/><br />
<p style="clear:left;">
<asp:Label ID="lbName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "productName")%>' /><br />
<asp:Label ID="lbUnitPrice" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "unitPrice")%>'/><br />
<asp:Label ID="lbRatings" runat="server" Text=''>Ratings</asp:Label><br />
<asp:LinkButton ID="linkCart" runat="server" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "productID")%>' CommandName="AddToCart">Add to Cart</asp:LinkButton>
</p>
</span>
</ItemTemplate>
</asp:Repeater>
As you can see I've added on the OnItemCommand in the Repeater tag so that this is invoked whenever one of the buttons(image/link) is fired. That works perfectly fine for both commandname AddToCart and ViewIndividProd. However, i want to store the the productid of a specific item that was invoked by the particular button. In my case now, it only stores ONE productid in the arraylist at a time and 'forgets' the productid that was stored previously when another linkbutton is clicked.
Question How do i make it such that everytime a linkbutton in the repeater is fired, it remembers the productid pertaining to the linkbutton that was fired and save these ids into the arraylist?
This is how the back end looks
ArrayList cart = new ArrayList();
protected void rptList_ItemCommand(object sender, RepeaterCommandEventArgs e) {
if (e.CommandName == "ViewIndividProd") {
Session["productID"] = e.CommandArgument.ToString();
Response.Redirect("IndividProduct.aspx");
}
if (e.CommandName == "AddToCart") {
string prodid = e.CommandArgument.ToString();
cart.Add(prodid);
Session["ShoppingCart"] = cart;
Response.Redirect("IndividCat.aspx");
}
msg.Text = "Shopping cart: " + String.Join(",", cart.ToArray());
}
Your feedback would be much appreciated.
You need to understand the Asp.net Page life cycle.
A new instance of your Page object is created on every request.
Values from your input are populated into it.
Your array list is getting recreated every time.
If you want the values to persist, you will have to store your arraylist in the ViewState or the Session
Refer: How to: Save Values in View State
void Page_Load(object sender, EventArgs e)
{
if (ViewState["arrayListInViewState"] != null)
{
PageArrayList = (ArrayList)ViewState["arrayListInViewState"];
}
else
{
// ArrayList isn't in view state, so we need to create it from scratch.
PageArrayList = CreateArray();
}
// Code that uses PageArrayList.
}
We can store comma separated or JSON value in either Session or hidden variable (If you are on the same page and opening new page in different tab then we can use hidden variable also). So every time an button has been click we can append the product id.