简体   繁体   中英

Databinding to a custom class in C#

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!

您必须使用属性进行绑定,而不是字段。

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; }
    }

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM