ASP.NET - VB - using String.Format for Custom Number formatting

I am needing some help.  I've been stuck on this too long not to ask now.

I have the following code in a GridView:
    <asp:TemplateField HeaderText="Report No." SortExpression="Reference_No">
                        <ItemTemplate>
                            <asp:Literal ID="LitRefNo" runat="server" Text='<%# String.Format("{0:##-######}", Int64.Parse(Eval("Reference_no").ToString()))%>' />
                        </ItemTemplate>
                    </asp:TemplateField>

Open in new window


The field Reference_No can contain 7-10 digits.  Is there a way to dynamically keep appending the end of the string if the number is actually longer than 7 digits?  (Mostly 8-9 digits are used)

Example:
Reference # may contain:  070006786
And output as: -70006786 or 7-0006786 if I removed a placeholder #
The correct output should be:  07-0006786  
However the string length may change to be a number like:
90005372  (which I would want formated as:  90-005372)

I have also tried creating a function to check the length but I get errors regarding parsing a databinded field using Eval.
 'Public Function FormatReport(RepNum) As String
    '    If Len("Reference_No") = 8 Then
    '        String.Format("{0:##-######}", Int64.Parse(Eval("Reference_no").ToString()))
    '    Else
    '        String.Format("{0:##-#######}", Int64.Parse(Eval("Reference_no").ToString()))
    '    End If
    'End Function

Open in new window


Any help is a appreciated!  Please let me know if I am not clear in explaining my requirements.

Britt
Britt Priddy JrSoftware Systems AnalystAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

AndyAinscowFreelance programmer / ConsultantCommented:
Does something like this do what you want?
String.Format("{0:0#-######}"
Britt Priddy JrSoftware Systems AnalystAuthor Commented:
I have actually tried that and all it does it prepend the number with a 0.
It's crazy that I'm stuck on something that seems it would be simple.

Varied length string of numbers anywhere from 7 to 10 characters and I simply want to add a dash after to first two numbers.  I am sure there is another function available to use or to add to to accomplish this.  I just can't think of it.
it_saigeDeveloperCommented:
Honestly, what you are attempting is not best suited by using an integer type (you can check to ensure that it is an integer by using either an integer parse method or regular expression).  The reason I say this is because the parse method will strip off any leading zeros.  In reality you want to use a substring based method; something like:
Imports System.Text.RegularExpressions

Module Module1
	Sub Main()
		Dim testCases As List(Of String) = New List(Of String) From {"070006786", "90005372", "0123456789", "01234567", "12345678", "00123456", "00012345", "NonMatches", "123", "1234567890987654321"}

		Console.WriteLine("Using an Integer Parse Method:")
		For Each testCase In testCases
			UsingIntegerParse(testCase)
		Next

		Console.WriteLine()

		Console.WriteLine("Using a Regular Expression Match Method:")
		For Each testCase In testCases
			UsingRegularExpressionMatch(testCase)
		Next

		Console.ReadLine()
	End Sub

	Sub UsingIntegerParse(ByVal source As String)
		Dim temp As Integer = -1
		If Integer.TryParse(source, temp) AndAlso (source.Length >= 7 AndAlso source.Length <= 10) Then
			Console.WriteLine("{0}-{1}", source.Substring(0, 2), source.Substring(2, source.Length - 2))
		End If
	End Sub

	Sub UsingRegularExpressionMatch(ByVal source As String)
		Dim matches As MatchCollection = (New Regex("[0-9]{7,10}")).Matches(source)
		If matches.Count = 1 Then
			Console.WriteLine("{0}-{1}", matches(0).Value.Substring(0, 2), matches(0).Value.Substring(2, matches(0).Value.Length - 2))
		End If
	End Sub
End Module

Open in new window

Which produces the following output -Capture.JPG-saige-
HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

Britt Priddy JrSoftware Systems AnalystAuthor Commented:
Thanks saige!
I believe you know exactly what I am trying to do.
This is also true:
 The reason I say this is because the parse method will strip off any leading zeros.
It has been stripping off the leading zeros and I had no idea why.

How would I implement this into some type of function that would reference the field I am trying to format in a dynamic manner. i.e., adding the - (dash) after the first two digits and allow however many left spill out after.  I am doing this in a web application  in VB  (.aspx)

The code I show in my Gridview seems so simple but being not all numbers in that field are the same length - bottlenecked me.  My lack use / knowledge / keeping up has me stumped on how to even implement what you've provided, which works and is exactly the results I am looking for.
it_saigeDeveloperCommented:
Without knowing how you retrieve your data, my first thought is to use the Page_Load event and set the text of the Literal using a code-behind method; e.g. -
Public Class _Default
	Inherits System.Web.UI.Page

	Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
		Literal1.Text = GetReferenceNumber("070006786")
	End Sub

	Protected Function GetReferenceNumber(ByVal source As String) As String
		Dim result As String = String.Empty
		Dim matches As MatchCollection = (New Regex("[0-9]{7,10}")).Matches(source)
		Try
			If matches.Count = 1 Then
				result = String.Format("{0}-{1}", matches(0).Value.Substring(0, 2), matches(0).Value.Substring(2, matches(0).Value.Length - 2))
			End If
		Catch ex As Exception
			result = String.Empty
		End Try
		Return result
	End Function
End Class

Open in new window

With the Literal being modified as such -
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="EE_Q28708505_Web._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
	<title></title>
</head>
<body>
	<form id="form1" runat="server">
		<div>
			<asp:Literal ID="Literal1" runat="server" />
		</div>
	</form>
</body>
</html>

Open in new window

Obviously, this line - Literal1.Text = GetReferenceNumber("070006786")

Would need to be edited so that you would use your "Reference_no" field value instead.  This, however, depends on how and where you retrieve your data.

-saige-

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Britt Priddy JrSoftware Systems AnalystAuthor Commented:
Awesome -saige-!!!   I really appreciate your help as well as helping me understand.
This work perfectly and is exactly what I was trying to accomplish.
Great job and thanks again!
Britt Priddy JrSoftware Systems AnalystAuthor Commented:
Extremely quick to understand needs and able to provide examples you can understand and learn from.  Very intelligent expert!  
I really appreciate you help.
it_saigeDeveloperCommented:
Glad to be of assistance.

-saige-
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.