Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Binding data textbox format

Status
Not open for further replies.

kyledunn

Programmer
Jan 2, 2001
145
0
0
US
I'm binding a textbox to a Currency data type in a Microsoft Access database. Everything works as expected except for the format of the currency field in the text box. I want to display 2 decimal places like #.##. No matter what I enter or routines I add will work to append .00 to the text box string when the value is even dollars. The binding seems to strip away any zeros. 10.10 becomes 10.1, 20.00 becomes 20. Any ideas how I can solve this?
 
Hey Kyle,

Well, off the top of my head you could have a method that parses the number, finds the decimal, and counts how many places are after it. If there is only one, then you could append a 0 to it. If its none, then you could append two 0's. Of course, that means that your dealing with the data as a string, but if its just being shown from a db, and you have other error checking to make sure its valid before being saved, it shouldn't be an issue.

Jack
 
I found the answer and thought I'd post it to possibly save someone else from the struggle I had. When binding to the access database you must create ConvertEventHandlers to intercept the Format and Parse that occur automatically during the binding process.

First create a separate binding:

Binding b = new Binding("Text",dataview,"AccessDatabaseColumnName");

Then create new ConvertEventHandlers for the Format and Parse events that occur during binding:

b.Format += new ConvertEventHandler(DecimalToCurrencyString);
b.Parse += new ConvertEventHandler(CurrencyStringToDecimal);

Then bind the datacolumn to the textbox:

TextBox1.DataBindings.Add(b);

Here are the conversion functions:

private void DecimalToCurrencyString(object sender, ConvertEventArgs cevent)
{
if(cevent.DesiredType != typeof(string)) return;
cevent.Value = ((decimal) cevent.Value).ToString("c");
}

private void CurrencyStringToDecimal(object sender, ConvertEventArgs cevent)
{
if(cevent.DesiredType != typeof(decimal)) return;
cevent.Value = Decimal.Parse(cevent.Value.ToString(),NumberStyles.Currency, null);
}

Make sure to reference System.Globalization to cover NumberStyles.Currency.

using System.Globalization;

Now a decimal field stored in an Access database will convert to a Currency format in a textbox.

Kyle
 
What namespace is Binding in? I find DataBinding in RC3 but no Binding.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top