Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winforms Data Binding to Custom Class

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.

like image 807
Tinkerer_CardTracker Avatar asked Oct 23 '11 00:10

Tinkerer_CardTracker


1 Answers

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.

like image 78
Julien Poulin Avatar answered Nov 01 '22 22:11

Julien Poulin