AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=280&pId=-1
Custom Formatting of Strings
page
by Pani Baruri & Abhijit Mandrekar
Feedback
Average Rating: 
Views (Total / Last 10 Days): 16120/ 22

Custom Formatting of Strings : ToString Implementation

The solution to the problem is very simple. The followings are few approaches to solution.

 

  • Use inline code where required. Use left and right function to separate “hh” and “mm” respectively and then concatenate the strings with “:” character in between.

 

  • Write a common function “FormatHhMmString” that accepts string as input parameter to be formatted. Include the logic as above.

 

  • Write a class that has a shared method “FormatHhMmString” and include the logic from 1st bullet.

 

Imagine that you are storing the date also in simple string format as “mmddyyyy” with no slashes or hyphens in between or phone number as 10 digits with no slashes or hyphens in between. So now you will have to write the 2 functions FormatMmDdYyyyString and FormatTelPhoneString or inline code wherever required.

 

If every developer writes the inline code then there will not be unique approach to come up with the solution. If you write a class then each time there is new user defined format there will be a new method added to the class.

 

ToString Implementation:

To wrap up all we need to do is define a class which implements IFormattable interface and its version of ToString function to custom format the strings. This approach allows developers to use standard ToString function transparently leaving implementation details behind the scene.

 

The ToString function accepts two parameters: the first parameter is a format string (custom format specification) and the second parameter is format provider object. The format provider object usually carries additional information specific to culture, date & time, numbers of targeted users. To keep things simple we will pass Nothing to format provider and apply general (default) formatting to strings when Nothing is passed.

 

The code that implements above scenarios is as follows:

 

Class Code:

Public Class FormatClass

Implements IFormattable

' Assign a value for the class.

Private _myValue As String

' Add a constructor.

Public Sub New(ByVal value As String)

_myValue = value

End Sub

' Write a custom Format method for the type.

Public Overloads Function ToString(ByVal format As String, ByVal fp As IFormatProvider) As String Implements IFormattable.ToString

If format.Equals("hhmm") Then

Return Left(_myValue, 2) & "-" & Right(_myValue, 2)

ElseIf format.Equals("mmddyyyy") Then

Return Left(_myValue, 2) & "-" & Mid(_myValue, 3, 2) & "-" & Right(_myValue, 4)

ElseIf format.Equals("9999999999") Then

Return Left(_myValue, 3) & "-" & Mid(_myValue, 4, 3) & "-" & Right(_myValue, 4)

Else

Return _myValue.ToString(fp)

End If

End Function

End Class

User Interface Code Behind:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim myTime As New FormatClass(TextBox1.Text)

Dim myDate As New FormatClass(TextBox2.Text)

Dim myTelNo As New FormatClass(TextBox3.Text)

Try

lblTimeToString.Text = myTime.ToString("hhmm", Nothing)

lblDateToString.Text = myDate.ToString("mmddyyyy", Nothing)

lbltelToString.Text = myTelNo.ToString("9999999999", Nothing)

Catch ex As Exception

Response.Write(ex.Message)

End Try

End Sub

User Interface (HTML):

<form id="Form1" method="post" runat="server">

<asp:label id="Label3" style="Z-INDEX: 100; LEFT: 386px; POSITION: absolute; TOP: 28px" runat="server" Height="22px" Width="66px">Enter time</asp:label>

<asp:button id="Button2" style="Z-INDEX: 109; LEFT: 495px; POSITION: absolute; TOP: 150px" runat="server" Height="23px" Width="213px" Text="Use ICustomFormatter Interface"></asp:button><asp:textbox id="TextBox1" style="Z-INDEX: 101; LEFT: 471px; POSITION: absolute; TOP: 28px" runat="server" Height="28px" Width="99px"></asp:textbox><br>

<br>

<asp:label id="Label4" style="Z-INDEX: 102; LEFT: 302px; POSITION: absolute; TOP: 69px" runat="server" Height="24px" Width="149px">Enter date (mmddyyyy)</asp:label><asp:textbox id="TextBox2" style="Z-INDEX: 103; LEFT: 471px; POSITION: absolute; TOP: 66px" runat="server" Height="28px" Width="100px"></asp:textbox><br>

<br>

<asp:label id="Label5" style="Z-INDEX: 104; LEFT: 292px; POSITION: absolute; TOP: 109px" runat="server" Height="24px" Width="151px">Enter Tel No (10 digits)</asp:label><asp:textbox id="TextBox3" style="Z-INDEX: 105; LEFT: 471px; POSITION: absolute; TOP: 106px" runat="server" Height="26px" Width="102px"></asp:textbox><br>

<br>

<asp:button id="Button1" style="Z-INDEX: 107; LEFT: 286px; POSITION: absolute; TOP: 150px" runat="server" Height="23px" Width="189px" Text="Use IFormattable Interface"></asp:button>

<asp:table id="Table1" style="Z-INDEX: 108; LEFT: 287px; POSITION: absolute; TOP: 193px" runat="server" Height="58px" Width="460px">

<asp:TableRow>

<asp:TableCell Text="ToString Formatting"></asp:TableCell>

<asp:TableCell Text="String.Format Function"></asp:TableCell>

</asp:TableRow>

<asp:TableRow>

<asp:TableCell>

<asp:label id="lblTimeToString" runat="server" Height="22" Width="189"></asp:label>

</asp:TableCell>

<asp:TableCell>

<asp:label id="lblStringFormat" runat="server" Height="22" Width="189"></asp:label>

</asp:TableCell>

</asp:TableRow>

<asp:TableRow>

<asp:TableCell>

<asp:label id="lblDateToString" runat="server" Height="22" Width="189"></asp:label>

</asp:TableCell>

<asp:TableCell></asp:TableCell>

</asp:TableRow>

<asp:TableRow>

<asp:TableCell>

<asp:label id="lblTelToString" runat="server" Height="22" Width="189"></asp:label>

</asp:TableCell>

<asp:TableCell></asp:TableCell>

</asp:TableRow>

</asp:table></form>

How to work with this example:

Type any 4 digit value in text box (associated label text=Enter time), type 8 digit value in text box (associated label text=Enter date), type 10 digit value in text box (associated label text=Enter Tel. No.) and click button that has a text "Use Iformattable Interface".

Input:

Time: 1234

Date: 02141965

Tel No.: 8562084721

Result:

Time: 12:34 (ToString Method)

Date: 02/14/1965

Tel No.: (856) 208-4721

Custom Formatting of Strings: String.Format Implementation

The custom formatting can also be achieved through the implementation of String.Format function. In order to do so we need to implement Format method of ICustomFormatter interface. This method accepts parameters such as format string, multiple values to be formatted, and format provider object. These parameters are compatible with one of the overloaded version of String.Format function. The advantage with this function is multiple values are formatted at once in a single function call.

To start with define a class which implements interface ICustomFormatter and IFormatProvider. When call is made to Format method it first gets the instance of ICustomFormatter by calling GetFormat function of IFormatProvider interface and uses it to format multiple arguments supplied to the function.

The simple method to form a format string is to concatenate argument number followed by format string and " :" as a separator between them. The arguments are numbered starting from 0. The arguments (input strings to be formatted) are stored in an array. The order of arguments and format strings must go hand-in-hand while coding. The following code illustrates other way to custom formatting.

Class Definition:

Public Class StringFormatClass

Implements IFormatProvider

Implements ICustomFormatter

Public Function GetFormat(ByVal service As Type) As Object _

Implements IFormatProvider.GetFormat

If service.ToString() = "System.ICustomFormatter" Then

Return Me

Else

Return Nothing

End If

End Function

' After String.Format gets the ICustomFormatter, it calls this format

' method on each argument.

Public Function Format(ByVal theFormat As String, ByVal arg As Object, ByVal fp As IFormatProvider) As String _

Implements ICustomFormatter.Format

If theFormat.Equals("hhmm") Then

Return Left(arg, 2) & ":" & Right(arg, 2)

ElseIf theFormat.Equals("mmddyyyy") Then

Return Left(arg, 2) & "/" & Mid(arg, 3, 2) & "/" & Right(arg, 4)

ElseIf theFormat.Equals("9999999999") Then

Return "(" & Left(arg, 3) & ") " & Mid(arg, 4, 3) & "-" & Right(arg, 4)

Else

Return arg.ToString()

End If

End Function

End Class

User Interface Code Behind:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

Dim formatStr As String = "{0:hhmm},{1:mmddyyyy},{2:9999999999}"

Dim stringformatObject = New StringFormatClass()

Dim args(2) As String

args(0) = TextBox1.Text

args(1) = TextBox2.Text

args(2) = TextBox3.Text

Dim myString As String = String.Format(stringformatObject, formatStr, args)

lblStringFormat.Text = myString

End Sub

How to work with this example:

Follow the same procedures as for the previous example and click button that has text "Use ICustomFormatter Interface". The result will be same however the formatted values are separated by comma. It is to the discretion of developer how to separate them and put to use appropriately.


Product Spotlight
Product Spotlight 

©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-19 5:02:38 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search