【问题标题】:How to call an string extension method on a DataField in BoundField element?如何在 BoundField 元素中的 DataField 上调用字符串扩展方法?
【发布时间】:2011-10-20 11:46:42
【问题描述】:

想象一下,我在字符串类型上引入了一个名为 Shorten() 的扩展方法,它只获取前 50 个字符并返回它。

如果我想在 GridView 的绑定字段上调用此方法,调用它的最简单方法是什么,以便在屏幕上看到消息的缩短版本。

<!-- TODO: How to call .Shorten() extension method on the ItemDescription in markup: --!>
<asp:BoundField HeaderText="Items" DataField="ItemDescription"...> 

【问题讨论】:

    标签: c# asp.net .net data-binding extension-methods


    【解决方案1】:

    将该列设为模板列:

    <itemtemplate>
    <asp:label id="lblItemDesc" runat="server" Text='<%=string.Format(Eval("ItemDescription").ToShorten()))%>' />
    </itemtemplate>
    

    并确保 ToShorten 采用对象,而不是字符串,因为 Eval 返回对象。

    *以上代码未经测试,但可以肯定非常接近。

    另一种选择:

    修改你的类并添加一个ItemDescriptionShorten 属性,如下所示:

    public string ItemStringDescriptionShorten { get {return ItemDescription.ToShortern();}}
    

    现在绑定到该属性而不是 ItemDescription

    【讨论】:

      【解决方案2】:

      在 .aspx 文件的顶部,导入包含您的扩展方法的类所在的命名空间:

      <%@ Import Namespace="your namespace" %>
      

      然后:

      <asp:TemplateField HeaderText="Items">
                          <ItemTemplate>
                              <%# Convert.ToString(Eval("ItemDescription")).Shorten() %>
                          </ItemTemplate>
                      </asp:TemplateField>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-11
        • 2013-02-15
        • 2010-11-25
        • 2014-12-30
        相关资源
        最近更新 更多