I am binding some data to control, but want to limit the number of character of a specific field to a 30 first characters.
I want to do it, if it's possible, on aspx page.
I tried this:
Text='<%# String.Format("{0}", Eval("Title")).Substring(0,30) %> '
But got this error:
Index and length must refer to a location within the string. Parameter name: length
As Simon says, you'll encounter this error when the string is less than 30 characters.
You can write a protected method in your page -
protected string GetSubstring(string str, int length)
{
return str.Length > length ? str.Substring(0, length) : str;
}
Call it from the aspx code like this -
Text='<%# String.Format("{0}", GetSubstring(Eval("Title").ToString(), 30) %>'
This error occurs when your string isn't at least 30 chars long. You sould check it first and then cut off the chars you don't need as you did in your code snippet.
String s = "hello";
if(s.Length > 30)
{
s.Substring(0,30);
}
And in one line:
s.Length > 30? s.Substring(0,30) : s;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With