Saturday, September 27, 2008

Avoid Triming Of spaces inbetween words In GridView

Hi

This the Solution I found For the Following Problem

Normally You Will Find That When You have any dataentry form in asp.net with GridView you have many fields in that
suppose you have field of First Name and submit button

If you enter the Name as eg. Mrugank Dholakia and submit it It will be saved in database same way
if you again add the same name with spaces eg Mrugank Dholakia and submit it It will saved in database

But When You will see in the GridView It will Look Same as

Mrugank Dholakia
Mrugank Dholakia

Actucally It stores second one in database with spaces but still this is the situation

What Happens behind this is the problem of Browser IE and Mozilla which automatically trims the extra spaces between the words

To avoid this This is the below mention solution

1 )First While Featching From the Database you have to Replace spaces with using Replace function of Asp.NET

Variable.Replace(" "," ");

2) User The HtmlDecode method of HTTPServer Utility

Server.HTMLDecode(Variable);

Here variable is the value comming from the database


Sample Code:

protected void gvCustNames_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
String str=Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Name"));

str=str.Replace(" ", " ");
((
Label)(e.Row.FindControl("lblName"))).Text = Server.HtmlDecode(str);
}
}


Regards
Mrugank Dholakia

(MCA) Software Engineer

No comments: