Getting a substring of a bound value

I bind some data for control, but I want to limit the number of characters in a particular field to 30 with the first characters.

I want to do this, if possible, on an aspx page.

I tried this:

Text='<%# String.Format("{0}", Eval("Title")).Substring(0,30) %> ' 

But this error turned out:

The index and length must refer to the location within the string. parameter name: length

+4
source share
3 answers

As Simon says, you will encounter this error when a string is less than 30 characters.

You can write a protected method on your page -

 protected string GetSubstring(string str, int length) { return str.Length > length ? str.Substring(0, length) : str; } 

Call it from aspx code as follows:

 Text='<%# String.Format("{0}", GetSubstring(Eval("Title").ToString(), 30) %>' 
+7
source

This error occurs when the string length is at least 30 characters. You will check it first, and then turn off the characters that you do not 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; 
+1
source

A substring takes an initial index and length. Therefore, you must make sure that the string is at least 30 char, otherwise it will give an error.

0
source

Source: https://habr.com/ru/post/1309314/


All Articles