Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving substring of a bound value

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

like image 691
shivesh Avatar asked Feb 27 '23 01:02

shivesh


2 Answers

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) %>'
like image 60
Kirtan Avatar answered Mar 07 '23 01:03

Kirtan


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;
like image 38
Simon Avatar answered Mar 07 '23 01:03

Simon