2

Context

I recently wrote a final exam that required using a BindingSource object with ADO.NET to populate a number of combo box and label controls from which the user could perform basic business functions. I got it working but had some reservations about my design choice.

The setup

When a user selected a product from the combo box, the binding updated two labels of the cost and quantity-on-hand of the product. I then decimal-parsed the cost from the label's Text property to pass on to a purchase form.

The problem

I initially coded a SelectedIndexChanged event for the combo box control and then invoked a method to calculate a purchase total. However, I realized that it was taking the cost label's Text value before the binding updated the value, leaving an index lag (i.e. the calculated cost was for the previously-selected product).

My fix was to invoke the calculate method upon the cost label's TextChanged event instead of the combo box's SelectedIndexChanged event. It worked, but felt I compromised a design principal somewhere.

My question

What would be a better way to do this? I can see several possible avenues:

  • Can the binding source be called to immediately update associated fields before the calculate method is invoked?
  • Should I decant the cost value directly from the binding source using a parsed DataRowView ToString instead of sourcing it from a UI feature?
  • Is there a better way of getting values from a binding source other than the previous way that I don't know about?
  • Should I just dispense with the binding source and work with the DataTable object directly?

Appreciate any insight. Thanks!

Skannen
  • 23
  • 4

1 Answers1

3

Should I just dispense with the binding source and work with the DataTable object directly

That at least will basically solve your whole problem. Use your UI labels for displaying things only, not for providing input values for further calculations. What would you do, for example, if you get a requirement to change the formatting of the cost label, to, lets say values rounded to 1 decimal, but your cost calculation still needs to take care of 2 decimals?

In your case it is probably possible not to use the SelectedIndexChanged event of one of your UI controls, but to use the CurrentChanged event of your BindingSource, and get the cost value from of the Current property of the BindingSource (no need to parse any "ToString()" result here). That way, you can get the values and do any calculation you like without interfering with the UI controls.

Doc Brown
  • 199,015
  • 33
  • 367
  • 565