Objects in ArrayList (.NET 1.1)

mikeyK

Newcomer
Joined
Jul 6, 2004
Messages
1
Wondering if you could help...

say I have an object.

Code:
public class Product 
{
   private int _id = 0;
   private string _name = string.Empty;
   private string _desc = string.Empty;
   private double _cost = 0;
        
   public int Id 
   {
      set { _id = value; }
      get { return _id; }
   }

   public string Name 
   {
      set { _name = value; }
      get { return _name; }
   }

   public string Desc 
   {
      set { _desc = value; }
      get { return _desc; }
   }

   public double Cost 
   {
      set { _cost = value; }
      get { return _cost; }
   }

   public Product() { }

   public Product(int Id, string Name, string Desc, double Cost)
   {
      _id = Id;
      _name = Name;
      _desc = Desc;
      _cost = Cost;
   }
}

and I wanted to add objects into an ArrayList....

Code:
products.Add(new Product(1, "x", "x", 1.50));
products.Add(new Product(2, "x", "x", 2.00));
products.Add(new Product(3, "x", "x", 3.00));
products.Add(new Product(4, "x", "x", 4.00));
products.Add(new Product(5, "x", "x", 5.00));
products.Add(new Product(6, "x", "x", 6.00));

I then bind this arraylist to a radiobuttonlist or the like (ASP.NET) and all I have on postback is the Id of the product... How can I access this product in the arraylist from the id.... I've tried to use IndexOf and ovverided the Equals method in the Product Class with no luck... I've implemented a class of IComparer and tried to use BinarySearch but nothing hits these methods....

How should this be done? Should I use a different Collection class? Create a Custom ArrayList that ovverides IndexOf or am I missing something really simple? Thanks if you can help
 
Just create a method that will search for the Id...

C#:
Product GetProduct(int id)
{
    foreach(Product p in ProductArray)
        if(p.Id == id)
            return p;
    return null;
}

Product MyProduct = GetProduct(3);
Debug.WriteLine(MyProduct.Name);
 
Back
Top