Anthony
Anthony

Reputation: 39

ArgumentOutOfRangeException parameter name: Index

I keep getting this 'ArgumentOutOfRange exception non-negative number required, Parameter name: index', whenever I try to open the page and I can't seem to figure out where/how exactly the negative number is appearing. Thank you all in advance!!

var months = data.OrderBy(x => x.ApproximatedStartDate).Select(x => x.Month).Distinct((x, y) => x == y).OrderBy(x => x).ToList();
var upcomingMonths = months.GetRange(months.IndexOf(DateTime.Today.Month), months.Count - months.IndexOf(DateTime.Today.Month));

I'm getting the exception when the code reads the 'upcomingMonths' variable.

stack trace:

[ArgumentOutOfRangeException: Non-negative number required. Parameter name: index]
System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) +72
System.Collections.Generic.List`1.GetRange(Int32 index, Int32 count) +4951591
InitializeChartBC() 
Page_Load(Object sender, EventArgs e)
System.Web.UI.Control.OnLoad(EventArgs e) +103
System.Web.UI.Control.LoadRecursive() +68
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3811

Upvotes: 1

Views: 3329

Answers (1)

Rudresha Parameshappa
Rudresha Parameshappa

Reputation: 3926

According to Documentation header of the List

// Exceptions:
//   T:System.ArgumentOutOfRangeException:
//     index is less than 0.-or-count is less than 0.

So I think months doesn't contain Current Month. Before you call the months.GetRange check whether it contains current month and then call the GetRange.

var months = data.OrderBy(x => x.ApproximatedStartDate).Select(x => x.Month).Distinct((x, y) => x == y).OrderBy(x => x).ToList();
 //Anyone corrent me as the list is converted to **.ToList** it wont throw null error I feel
List<T> upcomingMonths = null;  //Where T is the type of the list
if(months.IndexOf(DateTime.Today.Month)>=0)
      upcomingMonths = months.GetRange(months.IndexOf(DateTime.Today.Month), months.Count - months.IndexOf(DateTime.Today.Month));

Upvotes: 3

Related Questions