Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Wondering if you could help...

 

say I have an object.

 

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....

 

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

Posted

Just create a method that will search for the Id...

 

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);

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...