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

dominicwong
dominicwong used Ask the Experts™
on
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.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
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
Most Valuable Expert 2012
Top Expert 2014
Commented:
Try following

   tbTxFrequency.DataBindings["Text"].Format += new ConvertEventHandler(ConvertHzToMHz);
   tbTxFrequency.DataBindings["Text"].Parse += new ConvertEventHandler(ConvertMHzToHz);

private void ConvertHzToMHz(object sender, ConvertEventArgs e)
{
  e.value = e.value / 1000000
}

private void ConvertMHzToHz(object sender, ConvertEventArgs cevent)
{
  e.value = e.value * 1000000
}

Author

Commented:
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;
Most Valuable Expert 2012
Top Expert 2014

Commented:
Use a messagebox to see what type e.value is at runtime.

Author

Commented:
Thanks CodeCruiser.

Author

Commented:
Thank you

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial