65.9K
CodeProject 正在变化。 阅读更多。
Home

避免 ASP.NET GridView 控件中多余空格的消除

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.67/5 (5投票s)

2008年11月6日

CPOL

1分钟阅读

viewsIcon

34465

本文档描述了如何避免在 ASP.NET GridView 控件中消除多余空格。

引言

我们经常会观察到 GridView 的一个“bug”,即我们在数据库中保存的字符串数据就像这样:“Testing    Testing1       Testing2    Testing123”,但当它在 GridView 中显示时,看起来却是“Testing Testing1 Testing2 Testing123”。
GridView 会消除多余的空格。这仅仅是因为浏览器解析 HTML 的方式。它不识别空格,只将   视为空格。

变通方法

如果您想避免 GridView 内部字符串类型数据自动消除多余空格,那么有一些解决方法。

1. BoundField

如果您正在使用 BoundField,那么请这样定义它。

<asp:BoundField DataField="description" DataFormatString="<pre>{0}</pre>" 
	HtmlEncode="False" />

此字段有两个重要的属性

  1. 保持 HtmlEncode=False
  2. DataFormatString 包含在 <pre></pre> 标签内

2. TemplateField

如果您正在使用 TemplateField,那么请这样定义您的模板字段。

    <asp:TemplateField ConvertEmptyStringToNull="False">
        <ItemTemplate>
            <pre ><asp:Label ID="Label1" runat="server" 
		Text='<%# Bind("description") %>'></asp:Label></pre>
        </ItemTemplate>
    </asp:TemplateField>

在这种情况下,需要设置一个重要的属性

  1. 将您的模板控件包含在 <pre></pre> 标签内(在上面的示例中,我将 Label 控件包含在 <pre></pre> 内)。

保存 HTML 友好的空格

如果您不想将 BoundField 或 TemplateColumn 包含在 <pre></pre> 标签内,那么您必须在将其保存到数据库时,手动将空格替换为 HTML 兼容的空格,即 &nbsp;。

一个非常简单的方法是使用字符串的 Replace 函数。就像这样

string str = "Testing    Testing1       Testing2     Testing123";
str.Replace(" ", "&nbsp;"); 

历史

  • 2008年11月6日:初始发布
避免 ASP.NET GridView 控件中多余空格的消除 - CodeProject - 代码之家
© . All rights reserved.