Question Using a binding source with a structure

Joined
Aug 21, 2010
Messages
8
Programming Experience
10+
Hi everyone. Found this forum yesterday and it looks like a great place to visit daily. It also looks like the place to pose this question.

I'm writing a order entry system and I'm using structures to pass information around various parts of the program for things like the order header (order date, customer name, etc).

In building the form I discovered that you could use a binding source between form controls and the struct which is great because it means alot less code on a form that will be very busy anyhow. Unfortunatly I'm either doing something wrong, or I've discovered a bug in vb.net because when you fill in a textbox and the binding source fires the setter for that attibute of the struct, it does one of two things. It either:

  1. Finds the struct that I assigned to the binding source then creates a new instance of it after it is done thus destroying any changes.
  2. Creates a new instance of the struct because it wants to rather than use the one I instructed.

I know this sounds confusing so I'm including a small program that demonstrates the problem I'm having.

Can anyone cast thier eyeballs over this and see if it's me doing something wrong and if so get me back on the right track?

Thanks much in advance
 

Attachments

  • exampleStructProblem.zip
    17.2 KB · Views: 23
Last edited by a moderator:
It's not a bug. It's a product of how value value types, i.e. structures, work. When you assign one variable to another, you make a copy of the contents of the variable. If it's a reference type then you're copying a reference, so you end up with two variables referring to the same object. If it's a value type then you're copying a value, so you end up with two objects that contain the same data.

When you data bind, the data is copied from the original data source, to the BindingSource, to the control. If the underlying items are value types then the copy you're editing via the control is not the copy in the original data source. Basically, don't bind value types unless you intend the data to be read-only.
 
Back
Top