I have this UI
with this code
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
namespace WinFormsComboBoxDatabinding
{
public partial class Form1 : Form
{
public List<Person> PersonList { get; set; }
public Person SelectedPerson { get; set; }
public Form1()
{
InitializeComponent();
InitializePersonList();
InitializeDataBinding();
}
private void InitializePersonList()
{
PersonList = new List<Person>
{
new Person { FirstName = "Bob", LastName = "Builder" },
new Person { FirstName = "Mary", LastName = "Poppins" }
};
}
private void InitializeDataBinding()
{
SelectedPerson = PersonList[0];
var bindingSource = new BindingSource();
bindingSource.DataSource = PersonList;
comboBox.DisplayMember = "FirstName";
//comboBox.ValueMember = "LastName";
comboBox.DataSource = bindingSource;
textBoxFirstName.DataBindings.Add("Text", SelectedPerson, "FirstName");
textBoxLastName.DataBindings.Add("Text", SelectedPerson, "LastName");
}
private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
SelectedPerson = comboBox.SelectedItem as Person;
Debug.WriteLine($"SelectedPerson: {SelectedPerson}");
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString()
{
return $"{FirstName} {LastName}";
}
}
}
I have two questions about databinding:
When I select Mary in the ComboBox, the two TextBox controls don't get updated. Why is that? What did I do wrong?
When I change the text "Mary" in the ComboBox, the SelectedPerson object doesn't get updated with the new FirstName, say "Mary changed", from the ComboBox. How would I achieve that behaviour of changing the ComboBox FirstName to update the FirstName of the SelectedPerson? Or is that not possible with a ComboBox?
Let me know if I need to add more details to the question.
You don't need the SelectedPerson variable. It looks like you just have the wrong DataSource wired up. Try it this way:
textBoxFirstName.DataBindings.Add("Text", bindingSource, "FirstName");
textBoxLastName.DataBindings.Add("Text", bindingSource, "LastName");