tags:

views:

428

answers:

4

Hi, I have a class like this:

public class Person
{
    Int32 id;
    Boolean isMarried = false;
    String displayName;
    Detail mainDetail = new Detail();
    Detail partnerDetail = new Detail();
}

public class Detail
{
    String firstName;
    String lastName;
    DateTime dob;
    String address;
}

And then a Form which has selected textboxes to show the information in the object. This is to be updated when the selected person is changed.

Now, for simple fields, such as displayName, this is a piece of cake:

txtTitle.DataBindings.Add("Text", selectedPerson, "displayName");

but how do I bind another TextBox to the firstName of the mainDetail property?

This attempt:

txtFirstNameMain.DataBindings.Add("Text", selectedPerson.mainDetail, "firstName");

returns a runtime error:

"Cannot bind to the property or column firstName on the DataSource. Parameter name: dataMember"

Thanks for your help!

A: 

Try this:

txtFirstNameMain.DataBindings.Add("Text", selectedPerson, "mainDetail.firstName");

I think that is the correct syntax.

Edit: That should be the correct syntax. See here for some documentation on the databinding property.

There may be one problem with your code though: You may not be able to use databinding against fields, so you may have to convert them to properties.

Rune Grimstad
+2  A: 

You have to use properties for binding, not fields.

Tadas
+1  A: 

you need to use public properties for databinding, like so:

  public partial class Form1 : Form
    {
        Person person;
        public Form1()
        {
            InitializeComponent();

            person = new Person();
            this.titleTextBox.DataBindings.Add("Text", person, "DisplayName");
            this.firstNameTextBox.DataBindings.Add("Text", person.MainDetail, "FirstName");
        }
    }

    public class Person
    {
        public Int32 ID { get; set; }
        public Boolean IsMarried { get; set; }
        public String DisplayName { get; set; }
        public Detail MainDetail { get; set; }
        public Detail PartnerDetail  { get; set; }

        public Person()
        {
            MainDetail = new Detail();
            PartnerDetail = new Detail();
        }
    }

    public class Detail
    {
        public String FirstName { get; set; }
        public String LastName { get; set; }
        public DateTime DateOfBirth { get; set; }
        public String Address { get; set; }
    }
Hath
A: 

Windows forms databinding works against properties and does not support fields. The properties you bind to should also be declared as public.

Mike J