I'm attempting to make a cart system for my C# based website using ASP.NET.
Currently I've created a method which updates a linkbutton which I have in the master page.
When I try and reference the linkbutton in a product page it errors saying 'productpages_stand' does not contain a definition for 'lbnCart' and no extension method 'lbnCart' accepting a first argument of type 'productpages_stand' could be found'.
Am I not able to link a linkbutton to a masterpage from a web form?
The method:
private void updateCartSummary()
{
// get number of items in cart and show summary in link button
ArrayList cart = (ArrayList)Session["CART"];
int totalItems = cart.Count;
this.lbnCart.Text = "Cart : " + "(" + totalItems + ")";
}
Link button from masterpage:
<asp:LinkButton ID="lbnCart" CssClass="shoppingcarttext button small third" runat="server">Cart : (0)</asp:LinkButton>
EDIT:
Main code segment which is erroring on the product page:
public partial class productpages_atomosninja : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // first time
{
updateCartSummary();
}
LinkButton lbnCart = (LinkButton)Master.FindControl("lbnCart");
if (lbnCart != null)
{
lbnCart.Text = "Cart : " + "(" + totalItems + ")";
}
}
protected void btnAtomos_Click(object sender, EventArgs e)
{
Trace.Warn("Adding an item to the cart");
// create cart item object with the book details
CartItem cartItem = new CartItem();
cartItem.setCost(299.00);
cartItem.setItemName("Atomos Ninja 2");
// extract arraylist from session variable
ArrayList arrCart = (ArrayList)Session["CART"];
// add the cartitem object to the arraylist
arrCart.Add(cartItem);
//store arrayList back into the session variable
Session.Add("CART", arrCart);
updateCartSummary();
}
private void updateCartSummary()
{
// get number of items in cart and show summary in link button
ArrayList cart = (ArrayList)Session["CART"];
int totalItems = cart.Count;
this.lbnCart.Text = "Cart : " + "(" + totalItems + ")";
}
}
Error for totalItems in the page_load method saying it doesn't exist since it isn't defined until later in the document.
EDIT 2:
After adding the code where #David said it still errors.
public partial class product : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // first time
{
updateCartSummary();
}
}
LinkButton lbnCart = (LinkButton)Master.FindControl("lbnCart");
if (lbnCart != null)
{
lbnCart.Text = "Cart : " + "(" + totalItems + ")";
}
}
While there is a relationship between the Master Page and the Content Page, this doesn't change how classes and properties and general scope work in the C# language. The Master Page and the Content Page are different classes, so you can't directly reference each other's class members like that.
However, the class for the Content Page does have a property on it called Master which references the Master Page. And that property can be used to access members of the Master Page object.
For example:
private void updateCartSummary()
{
// this part is unchanged from what you have
ArrayList cart = (ArrayList)Session["CART"];
int totalItems = cart.Count;
// here, find the control from the "Master" property
LinkButton lbnCart = (LinkButton) Master.FindControl("lbnCart");
if(lbnCart != null)
{
lbnCart.Text = "Cart : " + "(" + totalItems + ")";
}
}
Related
What I'm trying to do is: when a user clicks an item in a listbox, I want to get the item's ID number, which is an attribute. I then want to pass this ID to another page which will display the relevant data.
This is the code I have to attempt to do this:
private void lstCats_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Pets selectedAnimal = lstCats.SelectedItem as Pets;
NavigationService.Navigate(new Uri("/ViewPet.xaml?msg=" + selectedAnimal.ID, UriKind.Relative));
}
and then on the second page, where I want to display the data, I have the following:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string msg = "";
if (NavigationContext.QueryString.TryGetValue("msg", out msg))
{
id = Convert.ToInt16(msg);
DisplayDetails();
DisplayImage();
}
}
From what I can tell the problem lies on the first page, as the second page is working fine when linked to other pages, where I'm not using listboxes, etc.
Any help is appreciated. Thanks.
EDIT: The code I'm using to populate the listboxes:
private void DisplayCats()
{
foreach (Pets temp in thisApp.pets)
{
if (temp.Category.Contains("Cat"))
{
Animal animal = new Animal() { Details = temp.Name + "\n" + temp.Category + " / " + temp.Subcategory + "\n€" + temp.Price.ToString(), ImageURI = temp.Image };
lstCats.Items.Add(animal);
}
}
}
I believe that the issue is with this line:
Pets selectedAnimal = lstCats.SelectedItem as Pets;
The problem, here, is that your ListBox control has items that have Animals as their SelectedItems. What you will want to do is instead bind the ListBox with pets, instead of items:
private void DisplayCats()
{
foreach (Pets temp in thisApp.pets)
{
if (temp.Category.Contains("Cat"))
{
lstCats.Items.Add(temp);
}
}
}
Update
Assuming you want to bind with Animal objects, you can do the following:
private void DisplayCats()
{
foreach (Pets temp in thisApp.pets)
{
if (temp.Category.Contains("Cat"))
{
//note that I added the ID property --v
Animal animal = new Animal() { ID = temp.ID, Details = temp.Name + "\n" + temp.Category + " / " + temp.Subcategory + "\n€" + temp.Price.ToString(), ImageURI = temp.Image };
lstCats.Items.Add(animal);
}
}
}
Then your event handler should look like:
private void lstCats_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Animal selectedAnimal = lstCats.SelectedItem as Animal;
NavigationService.Navigate(new Uri("/ViewPet.xaml?msg=" + selectedAnimal.ID, UriKind.Relative));
}
Ok so the problem i am having is with a drop down list.
the drop down list is supposed to output (Drinklabel) the selected value, it dose this but only the first in the list (the drop down list is generated by session variable).
I would like it so i could use the drop down list, select new value then have the label (Drinklabel) update itself.
*code bellow *
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Drinklabel.Text = "Your Chosen Beverage is A " + DropDownList1.SelectedValue.ToString() + " Drink.";
}
////////////////////////////////////////////////////////////
Full about page code
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e)
{
MyFruit = Session["Fruitname"] as List<string>;
//Create new, if null
if (MyFruit == null)
MyFruit = new List<string>();
DropDownList1.DataSource = MyFruit;
DropDownList1.DataBind();
}
public List<string> MyFruit { get; set; }
protected void ButtonCalculate_Click(object sender, EventArgs e)
{
decimal total = calculatePrice(DropDownList1.SelectedItem.Text,
TextBoxQuantity.Text.Trim());
LabelResult.Text = "You would like " + TextBoxQuantity.Text.Trim() +
DropDownList1.SelectedItem.Text + "(s) for a total of $" +
total.ToString();
}
private decimal calculatePrice(string p1, string p2)
{
throw new NotImplementedException();
}
private decimal calculatePrice(string fruitName, int quantity)
{
// Ask the database for the price of this particular piece of fruit by name
decimal costEach = GoToDatabaseAndGetPriceOfFruitByName(fruitName);
return costEach * quantity;
}
private decimal GoToDatabaseAndGetPriceOfFruitByName(string fruitName)
{
throw new NotImplementedException();
}
}
you are not checking the session object before assigning it to the Local List MyFruit.
hence add a check before assigning the Session object
Replace this:
MyFruit = Session["Fruitname"] as List<string>;
With following:
if(Session["Fruitname"]!=null)
MyFruit = Session["Fruitname"] as List<string>;
and in your Question you said that you are able to get only one item from DropDownList always.
but here you are only assigning Session object one time so obviously you will get one item.
So finally.. I have my repeater working as I want it to be full of buttons, radio button, image buttons, update panels, AJAX modal popups and a heavy code behind each event.
found out that my repeater getting very slow when the items exceeds 20, so I used paging as a solution. the problem is when I do changes and move on to the next page, all changes are gone when getting back to the previous page. (checked radios, labels, etc all back to normal state).
please help, my system is in production now.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadTasks();
}
void loadTasks()
{
string evalidxxx = Request.QueryString["eval_id"].Trim().Replace(" ", "");
SqlConnection conn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["GappConnectionString2"].ConnectionString);
try
{
conn.Open();
SqlDataAdapter sqlAdapter = new SqlDataAdapter("SELECT Prog_Task_link.pt_seq, Tasks.task_name, Tasks.task_id FROM Tasks INNER JOIN Prog_Task_link ON Tasks.task_id = Prog_Task_link.task_id INNER JOIN Programs ON Prog_Task_link.prog_id = programs.prog_id INNER JOIN Data_Tracker_prepare ON Programs.prog_id = Data_Tracker_prepare.dtpre_prog_id WHERE Data_Tracker_prepare.eval_id =" + evalidxxx, conn);
System.Data.DataTable dt = new System.Data.DataTable();
sqlAdapter.Fill(dt);
PagedDataSource objPds = new PagedDataSource();
objPds.DataSource = dt.DefaultView;
objPds.AllowPaging = true;
objPds.PageSize = 10;
objPds.CurrentPageIndex = CurrentPage;
lblCurrentPage.Text = "Page: " + (CurrentPage + 1).ToString() + " of "
+ objPds.PageCount.ToString();
//Disable Prev or Next buttons if necessary
LinkPrevPage.Enabled = !objPds.IsFirstPage;
LinkNextPage.Enabled = !objPds.IsLastPage;
rptr1.DataSource = objPds;
rptr1.DataBind();
}
catch (SqlException ex)
{
Response.Write(ex.Message);
}
finally { conn.Close(); }
}
public int CurrentPage
{
get
{
// look for current page in ViewState
object o = this.ViewState["_CurrentPage"];
if (o == null)
return 0; // default to showing the first page
else
return (int)o;
}
set
{
this.ViewState["_CurrentPage"] = value;
}
}
protected void LinkPrevPage_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
loadTasks();
}
protected void LinkNextPage_Click(object sender, EventArgs e)
{
CurrentPage += 1;
loadTasks();
}
if you are using .net 4.0 you can use EnablePersistedSelection="True"
sorry to say but this can not be done..
When you are in page one, the rest pages are not actual exists in repeater.
after paging to next page next data will be load so previous data will be reset
i mean to say, When you ask to select all radios, buttons,check boxes are mean what you see. After you change page the other controls are set to default (probably unchecked or reset)
So re design your user interface for what you want to do. And as my suggestion take another button to save the current state of the page.. and then go to next page..
anything other that i can help ??
What I don't understand is, I have a pager_Create function, it is like that
public void createPager()
{
Div_Pager.Controls.Clear();
ImageButton left = new ImageButton(); left.ID = "leftButton";// +new Random().Next();
left.Click+=new ImageClickEventHandler(pager_Left_Click);
left.ImageUrl = "http://" + Request.ServerVariables["SERVER_NAME"] + ":" + Request.ServerVariables["SERVER_PORT"] + "/Teknik_raporlar/left.bmp";
ImageButton right = new ImageButton(); right.ID = "rightButton";// +new Random().Next();
right.Click+=new ImageClickEventHandler(pager_Right_Click);
right.ImageUrl = "http://" + Request.ServerVariables["SERVER_NAME"] + ":" + Request.ServerVariables["SERVER_PORT"] + "/Teknik_raporlar/right.bmp";
Div_Pager.Controls.Add(left);
Div_Pager.Controls.Add(right);
if (int.Parse(ViewState["NOP"].ToString()) <= 1) // Number of Pages
{
Div_Pager.Visible = false;
}
else
{
Div_Pager.Visible = true;
if (int.Parse(ViewState["CurrentPage"].ToString()) <= 1)
{
left.Visible = false;
}
if (int.Parse(ViewState["CurrentPage"].ToString()) >= int.Parse(ViewState["NOP"].ToString()))
{
right.Visible = false;
}
}
}
protected void pager_Left_Click(object sender, EventArgs e)
{
ViewState["CurrentPage"] = int.Parse(ViewState["CurrentPage"].ToString()) - 1;
}
protected void pager_Right_Click(object sender, EventArgs e)
{
ViewState["CurrentPage"] = int.Parse(ViewState["CurrentPage"].ToString()) + 1;
}
and what I don't understand is this, how come this pagers buttons not firing? I mean I am creating the same buttons everytime the pager is created. So how is it possible. What is its relation about page rendering. My simplified code is like this:
override Render()
{
function1()
}
Page_Load()
{
function1()
}
funtion1()
{
createpager()
}
You are creating & recreating dynamic controls , for normal controls event bindings works
if done is Page_Load() , but not for dynamically created controls.
you need to create dynamic controls in PreInit (or at least OnInit() & attach events there itself . Dynamic controls needs to be recreated on every post back.
Also u button ids need to be new every time,
like left.ID = "leftButton"+random_no.ToString();
Here is a best practices for creating controls dynamically.
http://www.singingeels.com/Articles/Dynamically_Created_Controls_in_ASPNET.aspx
Its long article , but plz go thru.
In my code I create the menu items dynamically:
string listClientID = BulletedList1.ClientID.Replace('_', '$');
int counter = 0;
foreach (DataRow dataRow in database.DataTable.Rows)
{
// Add Button
ListItem listItem = new ListItem();
listItem.Value = "buttonItem" + Convert.ToString(dataRow["rank"]);
listItem.Text = " " + Convert.ToString(dataRow["title"]);
listItem.Attributes.Add("onclick", "__doPostBack('" + listClientID + "', '"+ counter.ToString() +"')");
BulletedList1.Items.Add(listItem);
counter++;
}
This menu is inside a update panel:
<div id="MenuItemBox">
<asp:BulletedList
ID="BulletedList1"
runat="server"
OnClick="MenuItem_Click"
>
</asp:BulletedList>
</div>
What I want is when a listitem is clicked it performs a postback. But when I run this, the onclick event is only runned once.
For example. I have 4 listitems. When I click the first item the first time the onclick event is executed. Now I click the second item, the onclick event is also executed. But when I now click the first item again the onclick event is not fired.
When I check the error console in FireFox or Oprah I don't get any errors.
So my question is: how can I fix this and what am I doing wrong?
It seems you need to rebind it after postback.
Where do you add items to the menu and are you checking IsPostBack property?
Please compare html after first loading and postpack to see if _dopostback dissappear.
Then Try to remove IsPostBack check.
My code is working well.
Here is it.
public partial class _Default : System.Web.UI.Page {
protected void Page_Load (object sender, EventArgs e) { }
protected override void OnInit (EventArgs e) {
base.OnInit(e);
//if (!IsPostBack) {
string listClientID = BulletedList1.ClientID.Replace('_', '$');
int counter = 0;
List<SomeClass> items = new List<SomeClass>(){ new SomeClass() { Rank = 1, Title = "2"},
new SomeClass () {Rank = 2, Title = "Two"}};
foreach (var item in items) {
// Add Button
ListItem listItem = new ListItem();
listItem.Value = "buttonItem" + item.Rank;
listItem.Text = " " + item.Title;
listItem.Attributes.Add("onclick", "__doPostBack('" + listClientID + "', '" + counter.ToString() + "')");
BulletedList1.Items.Add(listItem);
counter++;
}
//}
}
protected void MenuItem_Click (object sender, BulletedListEventArgs e) {
Response.Write(e.Index);
}
class SomeClass {
public int Rank;
public string Title;
}
}
Probably UpdatePanel is causing the trouble. I would try pulling it out of UpdatePanel and then would see(which I believe it should) if that works?
Secondly, you can probably just populate the list items Values and Texts only, and then under mnuMainMenu_MenuItemClick(object sender, MenuEventArgs e) event; look for the specific item that has been clicked (e.Item.* public properties), and then probably would use Response.Redirect() to do the job; well, just thinking out loud...