ASP.NET Gridview truncate BoundField from code behind

103 views Asked by At

I am adding a dynamic column to an ASP.NET grid view.

Code to add the dynamic column:

List<DataControlField> columns; // this contains all gridview columns. 
BoundField boundField = new BoundField();
boundField.DataField = long_text_column.SortExpression;
boundField.SortExpression = long_text_column.SortExpression;
columns.Insert(0, boundField);

How can I trim / truncate long_text_column to show only first 15 characters on the UI.

NOTE: I do not want to trim at the database level for other reasons.

1

There are 1 answers

0
VDWWD On

I would add an extra property to the class with only a get that returns long_text_column with a max length of 15.

public class DataControlField
{
    public string long_text_column { get; set; }

    public string long_text_column_max15
    {
        get
        {
            if (!string.IsNullOrEmpty(long_text_column) && long_text_column.Length > 15)
                return long_text_column.Substring(0, 15);
            else
                return long_text_column;
        }
    }
}