Winforms Data Binding to Custom Class

13,147

You can use the DataBindings property of your controls (textbox, checkbox...) to add a binding to a specific control. For instance:

public Form1()
{
    InitializeComponent();
    TB_userName.DataBindings.Add("Text", userToBind, "name");
}

Also, IIRC, data binding only works on properties, so you'll first need to modify your UserInfo class accordingly. Moreover, if you want the UI to update automatically when modifying your objects in code, you must implement INotifyPropertyChanged in your custom classes.

Share:
13,147
Tinkerer_CardTracker
Author by

Tinkerer_CardTracker

Updated on June 24, 2022

Comments

  • Tinkerer_CardTracker
    Tinkerer_CardTracker almost 2 years

    I am trying to bind some Winform objects to a custom class, more specifically an instance of my custom class which I have added to the Form in the code. C#, .NET 2010 Express.

    For example, here is a fragment of the class, and the UserInfoForm

    public class UserInfo
    {
        [XmlAttribute]
        public string name = "DefaultName";
    
        [XmlAttribute]
        public bool showTutorial = true;
    
        [XmlAttribute]
        public enum onCloseEvent = LastWindowClosedEvent.Exit;
    }
    
    public enum LastWindowClosedEvent
    {
        MainMenu, 
        Exit, 
        RunInBackground
    }
    
    
    public partial class Form1 : Form
    {
        UserInfo userToBind = new UserInfo();
    
        TextBox TB_userName = new TextBox();
        CheckBox CB_showTutorial = new CheckBox();
        ComboBox DDB_onCloseEvent = new ComboBox();
    
        public Form1()
        {
            InitializeComponent();
        }
    }
    

    Now, I would like to bind the values of these form controls to their respective value in userToBind, but have had no luck. All the tutorials I can find are either way out of date (2002), or about binding controls to a dataset, or other type of database.

    I am obviously overlooking something, but I haven't figured out what.

    Thank you very much for any info you can share.

    More info: UserInfo is designed to be XML-friendly so it can be saved as a user profile. UserInfo will contain other custom XML classes, all nested under the UserInfo, and many controls will only need to access these child classes.

  • Richard C
    Richard C about 12 years
    I also found that the properties need to be public, internal did not work for me.
  • Chris M.
    Chris M. about 6 years
    This is an old post, but if someone winds up here, it is worth noting that you can now avoid the static strings in databinding - TB_userName.DataBindings.Add(nameof(TB_username.Text), userToBind, nameof(userToBind.name));