Link to home
Start Free TrialLog in
Avatar of dominicwong
dominicwong

asked on

How to format and parse a number to/from a TextBox in C#, .NET

Hi experts
I'd done some searches within Experts-Exchange but couldn't find the answer I need. I wonder if someone could help.

I have a TextBox. This TextBox is bound to a BindingSource, which in turn is bound to a data object. I am using two-way bindings.

The member stored in the data object is an integer, eg '412678000'. But it needs to be displayed in decimal up to 3 decimal points. eg. 412.678. (Basically, unit conversion)
Vice versa when user enters the number. He/she enters '412.678' but it shall be stored in the data object as  '412678000'.

My data binding code:
    tbTxFrequency.DataBindings.Add("Text", bindingSource, "TxFreq", true, DataSourceUpdateMode.OnPropertyChanged, "unknown");

I think I need to add two event handlers (one for Parse, one for Format) to the Data Binding,
eg.
      tbTxFrequency.DataBindings["Text"].Format += ConvertHzToMHz;
      tbTxFrequency.DataBindings["Text"].Parse += ConvertMHzToHz;

But I don't know how to write these event handlers. Could someone please help? Or should it be done by another way?

Thanks in advance.
Avatar of BuggyCoder
BuggyCoder
Flag of India image

you can use the format event of your Binding object, here is an example:-

http://msdn.microsoft.com/en-us/library/system.windows.forms.binding.format.aspx
ASKER CERTIFIED SOLUTION
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dominicwong
dominicwong

ASKER

Thanks CodeCruiser
I am afraid the code doesn't work. Please point to me what I'd done incorrectly.

(1) If I do as the code that was given. There is a compile error.
       private void ConvertHzToMHz(object sender, ConvertEventArgs e)
       {
             e.value = e.value / 1000000 <-- Compile error: Can not apply '/' to operands of type 'object' and 'int'
        }

(2)  If I cast it as follows, there is a run-time exception of 'InvalidCastException':
             e.Value = ((int)(e.Value)) / 1000000.0;
   or
             e.Value = ((decimal)(e.Value)) / 1000000.0;
Use a messagebox to see what type e.value is at runtime.
Thanks CodeCruiser.
Thank you