skip to Main Content

I am stumped on how a foreach loop could throw an index out of range.
I am working with the ebay api to get a list of items.
I can verify with QuickWatch in Visual Studio that the collection contains 200 items.

I have searched for duplicate questions, but none matched my case.

My code to retrieve the list of items:

public ItemTypeCollection GetMyActiveItems()
{
    GetMyeBaySellingCall myEbaySelling = new    GetMyeBaySellingCall(ApiContext);

    myEbaySelling.ActiveList = new ItemListCustomizationType();
    myEbaySelling.ActiveList.Sort = ItemSortTypeCodeType.ItemID;
    myEbaySelling.UnsoldList = new ItemListCustomizationType();
    myEbaySelling.UnsoldList.Sort = ItemSortTypeCodeType.ItemID;
    myEbaySelling.SoldList = new ItemListCustomizationType();
    myEbaySelling.SoldList.Sort = ItemSortTypeCodeType.ItemID;

    myEbaySelling.Execute();
    var items = myEbaySelling.ActiveListReturn.ItemArray;
    //checking collection here. I can iterate this just fine. 
    // with no errors. 
    foreach (ItemType item in items)
    {
        var x = item.Title;
    }
    return items; 
}

Then on the Controller I am simply return passing the model to the View:

public ActionResult Items()
{
    ItemTypeCollection items = service.GetMyActiveItems();
    return View(items);
}

Then on the view, I am simply iterating the items to output to the browser:

@using eBay.Service.Core.Soap;

@model ItemTypeCollection


@foreach (ItemType item in Model)
{ // This is where the debugger stops on the first item with Index out of range exception. 
    <div class="col-sm-6 col-md-4">
        <div class="thumbnail">
        <h4 class="text-center"><span class="label label-info"></span></h4>
        <img src="@item.PictureDetails.PictureURL[0]" class="img-responsive">
         <div class="caption">
            <div class="row">
                <div class="col-md-6 col-xs-6">
                    <h3>@item.Title</h3>
                </div>
                <div class="col-md-6 col-xs-6 price">
                    <h3>
                        <label>@item.BuyItNowPrice.Value.ToString()</label>
                    </h3>
                </div>
            </div>
            <p>@item.SubTitle</p>
        </div>
    </div>
</div>
}

2

Answers


  1. var items looks like a multidimensional array, try using a simple for loop based on actual number of items.

    Foreach will look for every element into the multidimensional array, including the ones that have no title property.

    Login or Signup to reply.
  2. I think you want to check to make sure the picture details exist and there are picture urls

    @if(item != null && item.PictureDetails != null && item.PictureDetails.PictureURL.Any())
    {
       <img src="@item.PictureDetails.PictureURL.FirstOrDefault()" class="img-responsive">
    } 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search