Simple Databinding through bindingsource - unable to cast datasource

19 Views Asked by At

In winforms application I add a class "Class1" with one property P1; on the main form I put a button, and specify databinding of the property "text" -> add project data source - from object - Class1.P1.

screenshot1

This puts on the form Class1BindingSource with the datasource = Class1. The goal is to have button's text auto-update whenever I change class1.p1, so somewhere in the code I put

Dim T1 as Class1 = Class1BindingSource.Datasource T1.P1 = "ABC"

If I debug and break at line 1, and look at the Class1BindingSource.Datasource, I see that it's in fact Class1.

screenshot2

But when line 1 runs, it results in an exception 'Unable to cast object of type 'System.RuntimeType' to type 'WindowsApp1.Class1'.' Why?

I also don't fully understand, with this binding to the object through the bindingsource, where is the instance of Class1. It's supposed to be the datasource of the bindingsource, which is how I tried to access it in the code above; but I don't fully understand where it is and when it's created.

I am able to achieve what I want if I instantiate Class1 and specify the binding in the code, without bindingsource; but I'm curious how it's supposed to work by using the designer and bindingsource.

0

There are 0 best solutions below