views:

544

answers:

2

Hi, using Telerik RadGrid* in a LINQ context, with ASP.NET/C#, how to truncate text to a maximum length when displaying in columns? By maximum, I mean if original string's length is shorter than the specified maximum length, no errors will raise.

I have seen many examples of this on the net, but it seems that the Container.DataItem used to achieve this is different when using LINQ. Sometimes we see DataItem as a method, sometimes not. Examples are usually using a DataSet.

Here's an example found (source) :

<asp:TemplateField HeaderText="Description">
  <ItemTemplate>
    <%# ValidateString(Container.DataItem("Description")) %>
  </ItemTemplate>
</asp:TemplateField>

And codebehind:

protected string ValidateString(object String)
{
  if ((String.ToString().Length > 50))
  {
    return String.ToString().Substring(0, 50) + "...";
  }
  else
  {
    return String.ToString();
  }
}

Thank you for the help.

(*) Or a normal GridView, supposed to be compatible.

+2  A: 

I would hook into the OnItemDataBound event and perform this in your code behind. Cast the data item as your custom object and query the property, something like the following (typing some from memory):

protected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
     if (e.Item is GridDataItem)
     {
          GridDataItem dataBoundItem = e.Item as GridDataItem;
          CustomObject o = e.Item.DataItem as CustomObject;

          if(o.Description.Length > 50)
          {
               dataBoundItem["Description"].Text = o.Description.Substring(0, 47) + "..."
          }
      }
}

Alternatively if you want to stick with the method you are using try the following in your aspx

<telerik:GridTemplateColumn>
     <ItemTemplate>
          <%# ValidateString(Eval("Description").ToString()) %>
     </ItemTemplate>
</telerik:GridTemplateColumn>
rrrr
A: 

The idea of rrrr of using ItemDataBound event was a good lead. But, by using a custom query with inner joins for populating my grid, I can't use the CustomObject property. I've used the dataBoundItem["ColumnName"] by modifying directly its text. In fact, the solution was simple!

Here's an example :

protected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
    if (e.Item is GridDataItem)
    {
        GridDataItem dataBoundItem = e.Item as GridDataItem;
        if (dataBoundItem["ColumnName"].Text.Length > 100)
        {
            dataBoundItem["ColumnName"].Text = dataBoundItem["ColumnName"].Text.Substring(0, 100) + "...";
        }
    }
}

Thanks to rrrr by the way!

elbaid