Format string with GridView


One user at ASP.NEt forum asked a question for how to format a 15 digit number(string) with two hyphen (-) inside at position 10 and 15.

It can be don easily in SQL:

SELECT  LEFT(@From,9) +’-‘+SUBSTRING(@From,10,5)+’-‘+RIGHT(@From,1)

The same can be done at the front end with string manipulation.

For the data column in GridView, we need to convert the BoundField to TemplateField first and apply the string.Insert to Eval at the designated position twice.

Text='<%# Eval(“rawCol”).ToString().Insert(9,”-“).Insert(15,”-“) %>’

We can see this in action below:

<asp:TemplateField HeaderText=”rawCol” SortExpression=”rawCol”>

<EditItemTemplate>

<asp:TextBox ID=”TextBox1″ runat=”server” Text='<%# Bind(“rawCol”) %>’></asp:TextBox>

</EditItemTemplate>

<ItemTemplate>

<asp:Label ID=”Label1″ runat=”server” Text='<%# Eval(“rawCol”).ToString().Insert(9,”-“).Insert(15,”-“) %>’></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:BoundField DataField=”col” HeaderText=”col” ReadOnly=”True”

SortExpression=”col” />

 

Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s