c# - 检索绑定(bind)值的子字符串

标签 c# asp.net data-binding

我正在绑定(bind)一些数据来控制,但想将特定字段的字符数限制为 30 个第一个字符。

如果可能的话,我想在 aspx 页面上完成。

我试过这个:

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

但是出现了这个错误:

Index and length must refer to a location within the string. Parameter name: length

最佳答案

正如 Simon 所说,当字符串少于 30 个字符时,您会遇到此错误。

你可以在你的页面中写一个 protected 方法-

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

像这样从 aspx 代码调用它 -

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

关于c# - 检索绑定(bind)值的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2802649/

相关文章:

wpf - 将 wpf listview 绑定(bind)到数据集......可能......?

c# - WPF 中的数独 - 我应该为表格使用什么基本元素?

c# - 如何提示一个新窗口显示所选项目的模型数据?

c# - ASP.net 中的静态文件和身份验证

c# - 无法实现具有约束的基于多个泛型参数的方法?

C# Mongodb 驱动程序 : Translate Action into an UpdateDefinition

javascript - 无法使用 datatable.js Ajax 添加行

c# - EF 中的多个 where 条件

asp.net - 使ASP.NET/IIS不缓存PDF文件的正确方法

c# - 如何将数据库中的数据公开以供查询?