views:

40

answers:

3

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

+1  A: 

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;
Simon
+3  A: 

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) %>'
Kirtan
can make it even better.protected string GetSubstring(object obj, int length){ string str = obj.ToString(); return str.Length > length ? str.Substring(0, length) : str;}----Text='<%# GetSubstring(Eval("Title"), 30) %>'Wht do u say?
Shoaib Shaikh
A: 

Substring takes a start index and a length. So you should make sure that the string is not less than 30 char otherwise it will give the error.

Wael Dalloul