2016-11-18
工具 Visual Studio 2015 with Update 3
因為 LiteralContent 是 HTML 內容,如果抓取部分字元顯示,可能造成 HTML Tag 不對稱,導致版面亂掉,需設法解決。
WebForm1.aspx 部分內容
<asp:ListView ID="ListView1" DataSourceID="ContactsDataSource" DataKeyNames="ContactID" runat="server" OnItemDataBound="ListView1_ItemDataBound"> <LayoutTemplate> <table cellpadding="2" width="640px" border="1" runat="server" id="tblProducts"> <tr runat="server"> <th runat="server">CName</th> <th runat="server">Content</th> </tr> <tr runat="server" id="itemPlaceholder" /> </table> <asp:DataPager runat="server" ID="ContactsDataPager" PageSize="12"> <Fields> <asp:NextPreviousPagerField ShowFirstPageButton="true" ShowLastPageButton="true" FirstPageText="|<< " LastPageText=" >>|" NextPageText=" > " PreviousPageText=" < " /> </Fields> </asp:DataPager> </LayoutTemplate> <ItemTemplate> <tr runat="server"> <td valign="top"> <asp:Label ID="CNameLabel" runat="Server" Text='<%#Eval("CName") %>' /> </td> <td valign="top"> <asp:Literal ID="LiteralContent" runat="server" Text='<%# Eval("LiteralContent") %>' /> </td> </tr> </ItemTemplate> </asp:ListView> |
WebForm1.aspx.cs部分內容
protected void ListViewLatest_ItemDataBound(object sender, ListViewItemEventArgs e) { Literal context = new Literal(); if (e.Item.ItemType == ListViewItemType.DataItem) { ListViewDataItem dataItem = (ListViewDataItem)e.Item; DataRowView rowView = (DataRowView)dataItem.DataItem; context = (Literal)dataItem.FindControl("LiteralContent"); string oldContext = context.Text; string newContext = RemoveHTMLTag(oldContext); // 若不判斷長度直接抓,會出現錯誤 if (newContext.Length > 100) { // 抓 100 字太多,會直接超出框框大小,看不到 "(略)" 字 context.Text = newContext.Substring(0, 50) + "...(略)"; } else { context.Text = newContext + "...(略)"; } } } public RemoveHTMLTag(string htmlSource) { htmlSource = Regex.Replace(htmlSource, @"<script[\d\D]*?>[\d\D]*?</script>", String.Empty); htmlSource = Regex.Replace(htmlSource, "<[^>]*>", String.Empty, RegexOptions.IgnoreCase); return htmlSource; } |
(完)
沒有留言:
張貼留言