截断 RadGrid 列中的文本

发布于 2024-08-18 18:17:01 字数 856 浏览 1 评论 0原文

在 LINQ 上下文中使用 Telerik RadGrid* 和 ASP.NET/C#,如何在列中显示时将文本截断至最大长度?最大,我的意思是如果原始字符串的长度短于指定的最大长度,则不会出现错误。

我在网上看到过很多这样的例子,但似乎使用 LINQ 时用于实现此目的的 Container.DataItem 是不同的。有时我们将 DataItem 视为一种方法,有时则不是。示例通常使用DataSet

这是找到的一个示例():

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

和代码隐藏:

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

谢谢您的帮助。

(*) 或者一个普通的 GridView,应该是兼容的。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

爱冒险 2024-08-25 18:17:01

我将挂钩 OnItemDataBound 事件并在后面的代码中执行此操作。将数据项转换为自定义对象并查询属性,如下所示(从内存中输入一些内容):

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) + "..."
          }
      }
}

或者,如果您想坚持使用正在使用的方法,请在 aspx 中尝试以下操作

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

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>
习ぎ惯性依靠 2024-08-25 18:17:01

使用 ItemDataBound 事件的 rrrr 想法是一个很好的引导。但是,通过使用带有内部联接的自定义查询来填充网格,我无法使用 CustomObject 属性。我通过直接修改其文本来使用 dataBoundItem["ColumnName"]。其实解决办法很简单!

这是一个例子:

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) + "...";
        }
    }
}

顺便感谢rrrr

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!

混浊又暗下来 2024-08-25 18:17:01

使用转换器也可以达到此目的。

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

转换器子字符串类:

    /// <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();
    }
}

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();
    }
}
萝莉病 2024-08-25 18:17:01

你的代码没问题。只需将“Container.DataItem”更改为“Eval”即可。并保持一切原样。然后尝试一下。我希望它能起作用...
所有赌注

现有:

<%# ValidateString(Container.DataItem("描述")) %>

变化:

<%# ValidateString(Eval("描述")) %>

Your codes are okay. Just change "Container.DataItem" to "Eval". And keep everything as it is. Then try it. I hope it will work...
All the bet

Existing:

<%# ValidateString(Container.DataItem("Description")) %>

Changes:

<%# ValidateString(Eval("Description")) %>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文