I can’t seem to see my error here. I know this isn’t the best way to go at it but I’m obligated to use Arraylist.
Anyhow I know that my arraylist contains the right elements and I want to find out if the property Number for my Item class is the same as ‘searchNr’.
If it is, I want to print out that element using ToString(). If I search for “107” (the Number property of my last element in the Arraylist, I do find it. Can’t find any of the other number properties though. Can I use anything other than the If statement like (Equals)?
public void Search(object sender, EventArgs e)
{
string searchNrString = searchTextBox.Text;
int searchNr = Int32.Parse(searchNrString);
foreach (Item product in item)
{
if (product.Number == searchNr) //if we find the number
{
resultTextBox.Text = ((Item)product).ToString();
}
else if ( product.Number != searchNr) //if we don't find the number
{
string debug;
debug = string.Format("Could not find the number {0} arraylist :{1}", product.Number, item.Count); //debug här!
resultTextBox.Text = debug;
}
}
}
You need to add a
breakstatement to exit the loop once you find the desired item:Otherwise you might find the item, but your loop continues till the end and thus the number no longer matches the subsequent items, causing your
elsestatement to be evaluated. That is why you constantly appear to find the last element in your list (i.e., the “107” entry).