String type data inside gridview : Preserve extra spaces
Here’s my problem…
Very often we face a gridview "bug" that when we are saving the string data in the database just like this
"Sanjeev sanjeev1 sanjeev2 sanjeev123"but when it is shown in the gridview it looks like this
" Sanjeev sanjeev1 sanjeev2 sanjeev123".
GridView eats up the multiple spaces. This is only because of the browser that parses HTML. For a browser “space” is nothing, it only considers the " " as space.
And we have a solution too…
If you want to keep your string type data inside gridview, with all the extra spaces that you have entered then there are some workarounds exist for it.
1. BoundField
In case if you are using the BoundField then define it in this way.
<asp:BoundField DataField="description" DataFormatString="<pre>{0}</pre>" HtmlEncode="False" />
There are two important properties of this field.
1. Keep the HtmlEncode=False
2. Inclose the DataFormatString inside the tag.
2. TemplateField
If you are using the TemplateField then define your template field in this way.
<asp:TemplateField ConvertEmptyStringToNull="False">
<ItemTemplate>
<pre ><asp:Label ID="Label1" runat="server" Text='<%# Bind("description") %>'></asp:Label></pre>
</ItemTemplate>
</asp:TemplateField>
There is one important property that needs to set in this case.
1. Enclose your template control inside <pre></pre> tag (in above example I have enclosed the Label Control inside <pre></pre>
Save the HTML friendly spaces
If you don't want to enclose BoundField or the TemplateColumn inside the <pre></pre> tags then you have to manually change the space with HTML compatible space i.e. at the time while saving it in database.
A very simple way is to use the Replace function of string. Just like this.
String str =
"Testing Testing1 Testing2 Testing123";
str.Replace(" ", " ");
If you liked this .....please drop ur valuable comments.. :)
This is great and of good help.
ReplyDeleteThanks for your valuable information.
ReplyDeleteIt was really of use to me.
-Prabakaran.K
www.usjobcareer.com
The No.1 Job and Career Search Portal
Thank you so much. This exactly what I wanted
ReplyDeleteGreat Help
ReplyDeleteThanks a lot, it was usefull for me.
ReplyDeleteThanks Dear Its really Help me lot...
ReplyDeleteKeep it up : - Nilesh Shimpi..... :)
i tried your asp:BoundField example. but it puts a box around the datafield. how do i get rid of the box?
ReplyDeleterichard aquilo jr
Very Helpful! Thank You!!!
ReplyDeleteplz tell me how to maintain format of gridveiw after use Dataformatstring in databound column.
ReplyDeleteWhen we apply Dataformatstring in my gridview
it destroy my old gridview formating.
it really helpful ,but still i have a problem that when i select this gridview information in a textbox it shows like this
ReplyDeletebut i want only
RICK & DEBBI EVERETT
thanks in advance
sushil chauhan