As was foretold, we've added advertisements to the forums! If you have questions, or if you encounter any bugs, please visit this thread: https://forums.penny-arcade.com/discussion/240191/forum-advertisement-faq-and-reports-thread/
Options

Can't get sorted list to work correctly C#/ASP.Net losing my mind

override367override367 ALL minionsRegistered User regular
edited March 2015 in Help / Advice Forum
So I'm taking a simple C# program and trying to put it into a web page for an assignment

I have a sorted list, kennel, it's defined like this and I have two test items added to start with
public partial class WebForm1 : System.Web.UI.Page
    {
        private List<Dog> kennel; 
        protected void Page_Load(object sender, EventArgs e)
        {
            kennel = new List<Dog>();
            kennel.Add(new Dog(1, "Ricky"));
            kennel.Add(new Dog(2, "James"));

        }

here's what Dog is
        public class Dog
        {
            private int tag;
            private string dogname;


            public Dog()
            {
            }

            public Dog(int tag, string dogname)
            {
                Tag = tag;
                Dogname = dogname;
            }

            public int Tag
            {
                get { return tag; }
                set { tag = value; }
            }


            public string Dogname
            {
                get { return dogname; }
                set { dogname = value; }
            }

        }


Now when I display the list into a label with a foreach loop
foreach (Dog doge in kennel)
            {
                lstDisplay.Text = lstDisplay.Text + "Tag: " + doge.Tag.ToString() + " Name: " + doge.Dogname + "<br />";

            }

The two test dogs show up just fine, exactly how I need

But when I go to add a new item to the list on a button press, it doesn't do it, displaying the list produces the same results

I've tried doing it with variables, I've even tried going extremely basic like this
        protected void btnAdmit_Click(object sender, EventArgs e)
        {
            kennel.Add(new Dog(3, "butts"));
        {

but it doesn't work. What's even more confusing to me is that the kennel.Count (which I have displayed in a label) shows me a count of 2 to start off with (the two predefined entries on pageload), goes to 3 when I add a new one, but stays at 3 no matter how many more times I hit the add button (and this even if I go so far to have two add buttons and one of them adds another predefined entry like this, to say nothing of using variables to define the tag and dogname)

I can't for the life of me figure out why this doesn't work
heres how the relevant controls are defined in the aspx
       <asp:TextBox ID="txtDogName" runat="server" style="margin-left: 15px" Width="110px"></asp:TextBox>
       <asp:Button ID="btnAdmit" runat="server" Text="Admit Dog" Width="210px" OnClick="btnAdmit_Click" />
         <div style ="float: right"><asp:Label ID="lstDisplay" runat="server" Height="211px" style="margin-left: 0px; margin-top: 0px" Width="190px" /></div>
I feel like I'm taking crazy pills

override367 on

Posts

  • Options
    override367override367 ALL minions Registered User regular
    oh, with a button
    protected void btnDisplay_Click(object sender, EventArgs e)
            {
    
                foreach (Dog doge in kennel)
                {
                    lstDisplay.Text = lstDisplay.Text + "Tag: " + doge.Tag.ToString() + " Name: " + doge.Dogname + "<br />";
    
                }
            }
    

    It correctly displays any items added on page load, but none added via button (even if I literally just cut it from the page load and paste it to the button)

    the button is firing correctly too because any other functions I put on it work fine (and adding an item to a list with it causes my list counter to update, however it only adds one item on the list counter no matter how many I try to add with the button)

  • Options
    bowenbowen How you doin'? Registered User regular
    Looks like you have a normal List and not a sorted List?

    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    override367override367 ALL minions Registered User regular
    err yeah I suppose so

    idk why the title of the assignment is sorted list, since it's not what I'm asked to do

  • Options
    bowenbowen How you doin'? Registered User regular
    Yeah this is the downfall of a web based project here.

    Nothing is really saved, and it's all reset back to the defaults of your original page load like kamiro said. So you have to keep that all in mind when designing those events and button clicks.

    It almost seems like the instructor is trying to make it easy on you guys by letting you do ASP and web based for your UI but ignores the key sticking point that they're basically stateless.

    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    bowenbowen How you doin'? Registered User regular
    Also, your button click only adds one dog, with the same ID and name, instead of taking from the textbox. Not sure if that was intentional or not.

    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    bowenbowen How you doin'? Registered User regular
    @override367 , have you considered adding a listbox to your page and then, as dogs are added/removed from the kennel, add or remove them from the listbox? Even a textbox would be enough, on add, clear the textbox and loop through your kennel and add the dogs' names to it on a line.

    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    override367override367 ALL minions Registered User regular
    edited March 2015
    hum that explains it

    then I don't know how to do this assignment, because I need to have buttons that display the current list, remove one specific item from the list, display the list in alphabetical order, and display the list by the tag value

    I don't know how to do that if it's stateless

    this is the example program:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    public partial class _Default : System.Web.UI.Page
    {
        private List<Furniture> products;    
    
         //   Private products As List(Of Furniture)
        protected void Page_Load(object sender, EventArgs e)
        {
                products = new List<Furniture>();
                products.Add(new Furniture("Econo Sofa", "Acme Inc.", 74.99M));
                products.Add(new Furniture("Pioneer Table", "Heritage Unit", 866.75M));
                products.Add(new Furniture("Retro Cabinet", "Sixties Ltd.", 300.11M));
        }
    
        protected void btnDisplay_Click(object sender, EventArgs e)
        {
    
            lblOutput.Text = "<table border='4' cellpadding='3' cellspacing='0' align='right'>";
            lblOutput.Text += "<tr><th>Name</th><th>Description</th><th>Cost</th></tr>";
            foreach (Furniture piece in products)
            {
                lblOutput.Text += "<tr><td>" + piece.Name + "</td><td> " + piece.Description + "</td><td> " + piece.Cost.ToString("c2") + "</td></tr>";
            }
            lblOutput.Text += "</table>";
        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            decimal cost;
            Decimal.TryParse(txtCost.Text, out cost);
            products.Add(new Furniture(txtName.Text, txtDescription.Text, cost));
    
        }
        protected void btnClear_Click(object sender, EventArgs e)
        {
            lblOutput.Text = "";
        }
        protected void btnClearList_Click(object sender, EventArgs e)
        {
            products.Clear();
        }
    	
    	
    }
    

    with furniture.cs in a seperate cs file in a different folder called App_Code (I dont know what that's about)
        private string description;
        private decimal cost;
    
    	public Furniture()
    	{
    	}
    
        public Furniture(string name, string description, decimal cost)
        {
            Name = name;
            Description = description;
            Cost = cost;
        }
    
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    
    
        public string Description
        {
            get { return description; }
            set { description = value; }
        }
    
    
        public decimal Cost
        {
            get { return cost; }
            set { cost = value; }
        }
    
    }
    

    override367 on
  • Options
    override367override367 ALL minions Registered User regular
    I believe sessions is the correct route, I'm going to go read up on that

  • Options
    override367override367 ALL minions Registered User regular
    edited March 2015
    I think I just might not be smart enough for this class, because these instructions aren't helping me at all

    uWK22JN.png

    So my pageload looks like this now
    if (!IsPostBack)
                {
                    Session["test"] = kennel;
                    kennel = new List<Dog>();
                    kennel.Add(new Dog(1, "Rick James"));
                    
                }
    

    I don't know if that's right, and if it is I don't know how to retrieve or manipulate it because everything from trying to display it to altering it causes a crash

    I'm not using the Me.IsPostBack because that doesn't seem to work in C# at all

    this is trying to add something to it
                kennel = Session["test"] as List<Dog>;
                kennel.Add(new Dog(2, "Robert Paulson"));
    

    override367 on
  • Options
    bowenbowen How you doin'? Registered User regular
    Basically in each function, you want to address your session object.

    So when your program/page loads you'd initialize your kennel into the session. Something like:
    page_load() {
        Session["kennel"] = new List<Dog>();
    }
    

    Then when you get to a button click you'd do:
    button_click() {
        var kennel = (List<Dog>)Session["kennel"];
        kennel.Add(new Dog(1, "Doge"));
    }
    

    Then when you click the button to display you'd do:
    button_click_display() {
        var kennel = (List<Dog>)Session["kennel"];
        foreach(...) {
            //do stuff
        }
    }
    

    I've never done ASP, but, if it's anything like non-asp c#, you'd need to cast your kennel back into its type in order to be able to use it.

    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    override367override367 ALL minions Registered User regular
    oh shit I just had to put the session down a few lines in the pageload and now it seems to be working

    hot damn I wish my professor would update his materials to c# instead of VB, or have labs, or lectures that say how to do anything, or respond to e-mails, or offer explanations instead of just deducting points

    so far so good

    thanks a lot!

  • Options
    BogartBogart Streetwise Hercules Registered User, Moderator mod
    The session variable is going to be the thing you're adding stuff to and removing stuff from on the page. The kennel list is just the instantiation of the list with two items, so instantiate the list first in the page load (on !IsPostback), add the initial items, then write kennels to the session variable.

    When you add stuff on the button click you'll want to add it to the session variable (after casting it into the right list of objects). Probably you can save yourself some time by having a function on the page called SessionKennels or something that will grab the session variable and cast it into the right thing. That way you can go SessionKennels.Add blah blah instead of casting Session["kennels"] into the right type every time you want to use it.

    The Me.IsPostback is a VB thing.

  • Options
    bowenbowen How you doin'? Registered User regular
    Yeah an alternative would be:
    ((List<Dog>)Session["kennel"]).Add(new Dog(1, "Doge"));
    

    Strongly typed languages are not so hot for web/stateless programming.

    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    override367override367 ALL minions Registered User regular
    Bowen this is the same professor I had last semester that you shared in my... annoyance with

  • Options
    BogartBogart Streetwise Hercules Registered User, Moderator mod
    edited March 2015
    So with something like this you would never need to cast the session variable as a list outside of the initial setting of its value in the non-postback page load bit. Then referring to SessionThings in code would grab the session variable, cast it, and let you treat it like a list of whatever.
    		public List<Thing> SessionThings {
    			get { return (List<Thing>)Session["SessionThings"]; }
    			set {
    				if (value == null) {
    					Session.Remove("SessionThings");
    				} else {
    					Session["SessionThings"] = value;
    				}
    			}
    		}
    

    Bogart on
  • Options
    override367override367 ALL minions Registered User regular
    edited March 2015
    the lecture for this assignment was 90 minutes about CSS and then an anecdote about working for harley davidson as I recall

    well that's not fair, he did talk about sessions, they're mentioned in the slides

    but just definitions, not practical instructions

    override367 on
  • Options
    bowenbowen How you doin'? Registered User regular
    Bowen this is the same professor I had last semester that you shared in my... annoyance with

    I suspected as much from the past few posts about it in chat and this thread.

    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    override367override367 ALL minions Registered User regular
    edited March 2015
    So something like
    kennel = Session["test"] as List<Dog>;
                int Tagnumber;
                int.TryParse(txtTagNumber.Text, out Tagnumber);
                if (kennel.Contains(Tagnumber))
                {
                    lblKennelCount.Text = "Merry Christmas";
                }
    

    doesn't seem to work, I take it you can't use list.Contains with a session variable?

    override367 on
  • Options
    bowenbowen How you doin'? Registered User regular
    edited March 2015
    Well List contains a list of dogs. You'd need a way to find it.

    For something like "contains" in a list, they're known to use the equals operator, so you'd need to overload a whole bunch of stuff. That's pretty advanced at this stage in the game, so you want to keep it simple.

    You'd want to loop through the list and see if you can find the tag number

    foreach dog in kennel, etc.

    bowen on
    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    override367override367 ALL minions Registered User regular
    edited March 2015
    foreach (Dog doge in kennel)
                if (doge.Tag == Tagnumber)
                {
                    lblKennelCount.Text = "Merry Christmas";
                }
    

    seems to work, now I can make it give the appropriate message in the appropriate place

    override367 on
  • Options
    bowenbowen How you doin'? Registered User regular
    Be careful with your brackets. Get in the habit of putting brackets around everything contained within its scopes.
    foreach(Dog doge in kennel)
    {
        if(doge.Tag == Tagnumber)
        {
            lblKennelCount.Text = "Merry Christmas";
        }
    }
    

    There was a pretty significant bug (heartbleed) caused exactly because of something like that.

    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    BogartBogart Streetwise Hercules Registered User, Moderator mod
    edited March 2015
    That code is essentially asking if the list of dogs contains an integer as one of its members, which is nonsense. You want a loop to cycle through each member of the list, and in the loop you'll ask if dog.Tag == TagNumber. If the tag numbers match, do a thing.

    EDIT: Posted before I saw your altered code.

    Also, seriously consider the code snippet I pasted above, as having a function do your casting for you is infinitely preferable than doing it every time you want to get at it. You don't really need kennel at all. Instantiate the session variable with a new list of whatever in the !IsPostback bit of the page load, then refer to your function that does the casting for you.

    Bogart on
  • Options
    override367override367 ALL minions Registered User regular
    programming assignments make me take a real hit at my self esteem because I feel like I haven't learned anything in the last 2 years

    I don't even know the basic terminology half the time

    and now I can't figure out how to remove things from lists, it just crashes

    I've been trying to do this assignment for something like 9 hours now

  • Options
    BogartBogart Streetwise Hercules Registered User, Moderator mod
    Post the code you've got that tries to remove the member of the list.

    And hang in there. Coding is hard, and learning is just failing slightly less often as you go.

  • Options
    bowenbowen How you doin'? Registered User regular
    edited March 2015
    programming assignments make me take a real hit at my self esteem because I feel like I haven't learned anything in the last 2 years

    I don't even know the basic terminology half the time

    and now I can't figure out how to remove things from lists, it just crashes

    I've been trying to do this assignment for something like 9 hours now

    You can't remove things from a list while it's being enumerated over in C#.

    There's a few ways to go about this, you can use a dictionary instead of a list, and use the tag number as the key and you can just remove it via the key with a simple call.

    The other option is to keep record of the item you want to remove, then remove it after you find it (and break out of your loop), making sure it was actually found.

    bowen on
    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    bowenbowen How you doin'? Registered User regular
    The other option is to use a classic for loop, since the list isn't enumerated, and you can remove it directly via the index.

    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    bowenbowen How you doin'? Registered User regular
    I still get tripped up by the enumerator/foreach/remove thing every few months.

    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    override367override367 ALL minions Registered User regular
    edited March 2015
    Bleh I gotta turn this in right this second, I got too much on my plate to spend any more time on this assignment

    hopefully he'll post the code of how it's supposed to be done before the midterm

    I really appreciate all the help, at least 6 out of 7 things on it work and I was 0 out of 7 before

    override367 on
  • Options
    override367override367 ALL minions Registered User regular
    I eagerly anticipate under grade comments some snide comment about maybe spending more time on it or some shit

    I wish I could go to bed

  • Options
    AngelHedgieAngelHedgie Registered User regular
    bowen wrote: »
    Yeah an alternative would be:
    ((List<Dog>)Session["kennel"]).Add(new Dog(1, "Doge"));
    

    Strongly typed languages are not so hot for web/stateless programming.

    I find that this is where properties really shine. Hide all your session monkeying in the getter and setter, then just use like a normal variable elsewhere.

    XBL: Nox Aeternum / PSN: NoxAeternum / NN:NoxAeternum / Steam: noxaeternum
  • Options
    bowenbowen How you doin'? Registered User regular
    I eagerly anticipate under grade comments some snide comment about maybe spending more time on it or some shit

    I wish I could go to bed

    It's really hard to learn if no one's teaching you.

    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    TofystedethTofystedeth Registered User regular
    bowen wrote: »
    programming assignments make me take a real hit at my self esteem because I feel like I haven't learned anything in the last 2 years

    I don't even know the basic terminology half the time

    and now I can't figure out how to remove things from lists, it just crashes

    I've been trying to do this assignment for something like 9 hours now

    You can't remove things from a list while it's being enumerated over in C#.

    There's a few ways to go about this, you can use a dictionary instead of a list, and use the tag number as the key and you can just remove it via the key with a simple call.

    The other option is to keep record of the item you want to remove, then remove it after you find it (and break out of your loop), making sure it was actually found.
    What I do a lot of time is basically
    tmpList = new List<SomeClass>();
    foreach(SomeClass thing in RealList)
    {
      if(someCondition == true)
      {
         tmpList.Add(thing);
      }
    } 
    foreach(SomeClass thing in tmpList)
    {
      RealList.Remove(thing);
    }
    

    steam_sig.png
  • Options
    bowenbowen How you doin'? Registered User regular
    bowen wrote: »
    programming assignments make me take a real hit at my self esteem because I feel like I haven't learned anything in the last 2 years

    I don't even know the basic terminology half the time

    and now I can't figure out how to remove things from lists, it just crashes

    I've been trying to do this assignment for something like 9 hours now

    You can't remove things from a list while it's being enumerated over in C#.

    There's a few ways to go about this, you can use a dictionary instead of a list, and use the tag number as the key and you can just remove it via the key with a simple call.

    The other option is to keep record of the item you want to remove, then remove it after you find it (and break out of your loop), making sure it was actually found.
    What I do a lot of time is basically
    tmpList = new List<SomeClass>();
    foreach(SomeClass thing in RealList)
    {
      if(someCondition == true)
      {
         tmpList.Add(thing);
      }
    } 
    foreach(SomeClass thing in tmpList)
    {
      RealList.Remove(thing);
    }
    

    If you've got LINQ available to you you can do this:
    RealList.RemoveAll(x => x.thatCondition == true);
    

    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Options
    TofystedethTofystedeth Registered User regular
    I have LINQ but have never gotten around to just sitting down and figuring out how and when to use it.
    Though I have used similar syntax in some other collections to return subsets so maybe I've been LINQing this whole time and didn't know it.

    steam_sig.png
  • Options
    TechnicalityTechnicality Registered User regular
    I've been doing this when I want to avoid making a temporary list:
    int i=0;
    while (i < list.Count)
    {
        if (someCondition == true)
        {
            list.Remove(list[i]);
        }
        else
        {
            i++;
        }
    }
    
    In future I'll have to use that sexy bit of LINQ though!

    Keep up the good work OP. With programming you never stop learning, so don't forget its supposed to be fun!

    handt.jpg tor.jpg

  • Options
    TofystedethTofystedeth Registered User regular
    Also feel free to drop by the programming thread in Moe's subforum so we can help explain concepts your prof won't.

    steam_sig.png
  • Options
    override367override367 ALL minions Registered User regular
    this assignment is done and graded (I got a D, no explanation as to what I was supposed to do to make it all work right)

    however dicking around with it I realized I don't actually have to delete the list, I can just recreate the list with every item on it except the one in the textbox

    that seems to work

Sign In or Register to comment.