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 IamaSherpa 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 1

Status
Not open for further replies.

kyledunn

Programmer
Jan 2, 2001
145
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?
 
Try using 0.00 instead of #.##. I believe # is reserved for placeholders that are OPTIONAL, whereas 0 is used for placeholders that are REQUIRED.
 
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
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top