Monday, 27 August 2012

Index and length must refer to a location within the string? in ASP.NET

This week, I will post an error and its solution for ASP.Net.
Some might think this error is quite easy to solve.

For me, I spent half day to figure out. :)
Let me share this.

I wanted to use Substring function
<%# DataBinder.Eval(Container.DataItem,".....").ToString().Substring(0,180)   %>

Error - Index and length must refer to a location within the string? in Asp.net


To fix this error,
You have to use Math.Min for length of Substring.

<%# DataBinder.Eval(Container.DataItem,".....").ToString().Substring(0,Math.Min(Eval(".....").ToString().Length,180))%>

Hope this helps