简体   繁体   English

截断RadGrid列中的文本

[英]Truncate text in RadGrid column

using Telerik RadGrid* in a LINQ context, with ASP.NET/C#, how to truncate text to a maximum length when displaying in columns? 在LINQ上下文中使用Telerik RadGrid *,使用ASP.NET / C#,如何在列中显示时将文本截断为最大长度? 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. 我在网上看到了很多这样的例子,但是当使用LINQ时,用于实现这一点的Container.DataItem似乎是不同的。 Sometimes we see DataItem as a method, sometimes not. 有时我们将DataItem视为一种方法,有时则不然。 Examples are usually using a DataSet . 示例通常使用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. (*)或普通的GridView,应该是兼容的。

I would hook into the OnItemDataBound event and perform this in your code behind. 我会挂钩OnItemDataBound事件并在你的代码中执行此操作。 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 或者,如果您想坚持使用您正在使用的方法,请在您的aspx中尝试以下操作

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

The idea of rrrr of using ItemDataBound event was a good lead. 使用ItemDataBound事件的rrrr的想法是一个很好的领导。 But, by using a custom query with inner joins for populating my grid, I can't use the CustomObject property. 但是,通过使用带有内部联接的自定义查询来填充网格,我无法使用CustomObject属性。 I've used the dataBoundItem["ColumnName"] by modifying directly its text. 我通过直接修改其文本来使用dataBoundItem["ColumnName"] 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! 感谢rrrr顺便说一下!

Your codes are okay. 你的代码没问题。 Just change "Container.DataItem" to "Eval". 只需将“Container.DataItem”更改为“Eval”即可。 And keep everything as it is. 并保持一切尽在掌握。 Then try it. 然后尝试一下。 I hope it will work... All the bet 我希望它能奏效......所有的赌注

Existing: <%# ValidateString(Container.DataItem("Description")) %> 现有: <%#ValidateString(Container.DataItem(“Description”))%>

Changes: <%# ValidateString(Eval("Description")) %> 更改: <%#ValidateString(Eval(“Description”))%>

Using a converter also works for this. 使用转换器也适用于此。

<UserControl.Resources>
    <myConverters:SubStringConverter x:Key="First50CharactersConverter" Length="50" ShowEllipse="True" />
</UserControl.Resources>
...
<telerik:GridViewDataColumn DataMemberBinding="{Binding Comments, Converter={StaticResource First50CharactersConverter}}" Header="Comments">

The converter substring class: 转换器子串类:

    /// <summary> Mimics the behavior of string.substring for use in XAML </summary>
public class SubStringConverter : IValueConverter
{
    /// <summary> the zero-based starting character position </summary>
    public int StartIndex { get; set; }

    /// <summary> The number of characters in the substring </summary>
    public int Length { get; set; }

    /// <summary> shows "..." if value was truncated after StartIndex</summary>
    public bool ShowEllipse { get; set; }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string valueString = value as string;
        if (string.IsNullOrWhiteSpace(valueString) == false)
        {
            if (Length > 0 && Length < (valueString.Length + StartIndex))
            {
                if (ShowEllipse)
                    return valueString.Substring(StartIndex, Length - 3) + "...";
                else
                    return valueString.Substring(StartIndex, Length);
            }
            else if (StartIndex < valueString.Length)
                return valueString.Substring(StartIndex);
            else
                return ""; //because startIndex must be past the length of the string
        }
        else
        {
            return value;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM