2011-10-20 31 views
0

想象一下,我在名爲Shorten()的字符串類型上引入了一個擴展方法,它只獲取前50個字符並將其返回。如何在BoundField元素的DataField上調用字符串擴展方法?

如果我想在GridView的綁定字段上調用此方法,調用它的最簡單方法是什麼,以便在屏幕上看到消息的縮短版本。

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

回答

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

0
在.aspx文件的頂部

,導入命名空間中包含擴展方法的類是:

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

然後:

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