Text Box Formatting

ReportsNerd

Active member
Joined
Nov 24, 2012
Messages
31
Programming Experience
3-5
Hi, I have text boxes on a form that read data from a MS access database. Most of the money and percent fields are currently set to double in the database and the date fields are returned with a full date/time format. I want to format the money fields like 1,253.00 the date fields like mm/dd/yyyy and the percent fields like 23.44

The code I am currently using is:

VB.NET:
f
TotalPmts.Text = myDataSet.Tables("Players").Rows(TheCorrectRowIndexOfTheTable_BasedOnTheSearchCriteria).Item(27).ToString

Help suggestions appreciated.
Thank you
 
Hi,

Have a try with these formatting examples:-

VB.NET:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim myPercentValue As Double = 0.2435
    Dim myMoneyValue As Decimal = Convert.ToDecimal(23.45)
    Dim myDateValue As Date = Now()
 
    'format to percentage
    MsgBox(myPercentValue.ToString("p"))
 
    'format to currency
    MsgBox(myMoneyValue.ToString("c"))
 
    'format to date types
    MsgBox(myDateValue.ToShortDateString)
    MsgBox(myDateValue.ToLongDateString)
End Sub

Hope that helps.

Cheers,

Ian
 
Last edited:
Firstly, to be precise, your TextBoxes don't read data from a database. They have no idea that the database even exists. You have a data adapter that reads the data from the database and it puts that data into a DataSet. You then get the data from the DataSet and display it in the TextBoxes. The TextBoxes don't even know about the DataSet. All they know is that they receive a String.

Given that you have a DataSet, or more specifically a DataTable, you should not use any code to specifically display a value in the TextBox. You should bind the DataTable to your controls and then the Binding object looks after the formatting, e.g.
BindingSource1.DataSource = myDataTable
TextBox1.DataBindings.Add("Text", BindingSource1, "NumberColumn", True, DataSourceUpdateMode.OnPropertyChanged, String.Empty, "c")
TextBox2.DataBindings.Add("Text", BindingSource1, "DateColumn", True, DataSourceUpdateMode.OnPropertyChanged, String.Empty, "dd/MM/yyyy")
Once the data is bound you can navigate from record to record by calling the MoveNext and MovePrevious methods of the BindingSource.

The MSDN Library provides information on all the standard and custom format strings for numbers, dates and times and those same format strings are used when data-binding, when calling ToString or String.Format and various other places besides. It's worth noting that the "p" format specifier for numbers displays values as a percentage of 1.0, e.g. the number 0.5 will be displayed as "50.00 %".
 
Thanks jmcilhinney and Ian. You both really helped me a lot. I switched my app to use the data bindings and the formatting within the binding object. Wow, this is great!
 
Back
Top