-1

I have created a list names AllCalendarEventInfo inside which I have 2 more lists. when I am trying to add a list into the first index of the list, it throws IndexOutOfRangeException

model.AllCalendarEventInfo[i].allEventDates.Add(date);

model.AllCalendarEventInfo[i].allCalendarDates.AddRange(model.AllDateList);

in these two lines. please help.

heres my code :

var i = 0;
model.event_dates = 
_iadminSettingsService.GetEventDatesByEventId(model.event_id);

foreach (var date in model.event_dates)
{
    var addDate = date.event_date_start;
    while (addDate >= date.event_date_start && addDate <= date.event_date_stop)
    {
        model.AllDateList.Add(new CalendarDates
        {
            Id = date.event_id,
            Date = Convert.ToDateTime(addDate)
        });
        if (addDate.HasValue)
        {
            addDate = addDate.Value.AddDays(+1);
        }

    }
    model.AllCalendarEventInfo[i].allEventDates.Add(date);
            model.AllCalendarEventInfo[i].allCalendarDates.AddRange(model.AllDateList);

    model.AllDateList.Clear();
            i++;
}

here are all the models :

public class CalendarDates
{
    public int Id { get; set; }
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", 
    ApplyFormatInEditMode = true)]
    public DateTime Date { get; set; }
}

public class AllCalendarEventInfo
{
    public AllCalendarEventInfo()
    {
        allCalendarDates = new List<CalendarDates>();
        allEventDates = new List<event_dates>();
    }
    public List<CalendarDates> allCalendarDates { get; set; }
    public List<event_dates> allEventDates { get; set; }
}

public class Event_ViewModel
{
    public Event_ViewModel()
    {
        AllDateList = new List<CalendarDates>();
        AllCalendarEventInfo = new List<AllCalendarEventInfo>();
    }


    public List<event_dates> event_dates { get; set; }
    public List<event_dates> allEventDates { get; set; }
    public List<CalendarDates> AllDateList { get; set; }
    public List<AllCalendarEventInfo> AllCalendarEventInfo { get; set; }

  }
Isma
  • 14,604
  • 5
  • 37
  • 51
  • How you init model.AllCalendarEventInfo? I think u only do model.AllCallendarEventInfo = new List(), so when u access AllEventDate you will hit IndexOutOfRangeException. – BeiBei ZHU Jan 25 '19 at 05:45

1 Answers1

0

You need to add a new AllCalendarEventInfo

To the model.AllCalendarEventInfo

before you try accessing it with an indexer. You are trying to access the first item in the list before you’ve even added anything to the list so the index is out of bounds.

So the code block after the while should start with

model.AllCalendarEventInfo.add(new AllCalendarEventInfo());
model.AllCalendarEventInfo[i].allEventDates.Add(date);    model.AllCalendarEventInfo[i].allCalendarDates.AddRange(model.AllDateList);
model.AllDateList.Clear();
        i++;

Sorry for the formatting, it’s from my phone

Neil.Work
  • 985
  • 7
  • 9