3

Using WinForms and data bindings.

I have a form containing a BindingSource component and I have set the DataSource property from the designer to a class:

public class MyClass
{
    public string MyString {get;set;}
}

Now, how do I get the MyClass object assigned to the BindingSource from source code?

I've tried casting the DataSource property of the BindingSource to MyClass, not working.

Additional notes

My problem seems to be that I set the DataSource from the WinForms Designer.
The DataSource is then set to the type MyClass and not an actual object.

So, is there an object created that I can access and modify from code so that values from the bounded object shows on the form's controls ?

Thank you.

Stécy
  • 11,951
  • 16
  • 64
  • 89

1 Answers1

1

To add an object data source in a WinForms application, from the menu choose Data > Add New Data Source. In the Data Source Configuration Wizard choose Object and click Next. Select the class you wish to use as a data source and click Finish. The public properties of the class should now appear in the Data Sources window.

Then after you do that create an instance of the class and assign it to the DataSource property. For example:

private void Form1_Load(object sender, EventArgs e)
{
    MyClass myClass = new MyClass()
    {
        MyString = "aaaa"
    };

    myClassBindingSource.DataSource = myClass;
}
TheBoyan
  • 6,802
  • 3
  • 45
  • 61
  • From what I understand I could bind to a simple class. – Stécy Dec 16 '11 at 14:25
  • Yes, you can bind certain controls to a class. Please read the following article for more information: http://msdn.microsoft.com/en-us/library/c8aebh9k.aspx – TheBoyan Dec 16 '11 at 14:29
  • Follow-up on your update: It's already wired in this way. The problem is that the DataSource property is set to the type of the object but not an actual object. – Stécy Dec 16 '11 at 15:05
  • I finally think I understood your question completely. I've updated the answer again. – TheBoyan Dec 16 '11 at 15:19
  • @Stécy - there's no way how to do that. But what's wrong with filling it from code. Is there any particular reason why you want to do that. – TheBoyan Dec 16 '11 at 17:03
  • There's one simple reason: to provide an environment where a "programmer" would only drag/drop components and controls on the design surface and setup properties. – Stécy Dec 16 '11 at 18:27