C# WinForm keeps multiple controls in sync with the same data source

Time:2021-12-8

When understanding the data binding of Windows Forms, the data binding of controls is generally to directly assign values to the properties of the control that can receive values, such as the text property of the text box. However, when doing some list data processing, the same data needs to be processed in multiple places, so it is more troublesome to assign values to the properties of each control one by one. By setting the data source binding on the control properties and using the feature of windows data change notification, as long as the control subscribing (setting the binding) can receive the data change notification.
Realize bidirectional data binding through DataBindings method


textBox1.DataBindings.Add("Text", trackBar1, "Value", true, DataSourceUpdateMode.OnPropertyChanged);

Implement the inotifypropertychanged interface to raise an event notification when the property value changes


private Serial serial;

public Form3()
{
    InitializeComponent();
    serial = new Serial();

    this.textBox1.DataBindings.Add("Text", serial, "Number", true, DataSourceUpdateMode.OnPropertyChanged);
}

private void button1_Click(object sender, EventArgs e)
{
    serial.Number += 1;
}
public class Serial : INotifyPropertyChanged
{
    private int number;

    public int Number
    {
        get { return number; }
        set
        {
            if (value != number)
            {
                number = value;
                NotifyPropertyChanged();
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Bindinglist implements the main interface required for bidirectional windows form data binding. By binding a BindingSource data source to a control, you can keep multiple controls synchronized

public partial class Form1 : Form
{
    private IList<Foo> foos;
    private BindingList<Foo> bindingList;

    public Form1()
    {
        InitializeComponent();
        dataGridView1.MultiSelect = false;
        //Data source
        foos = new List<Foo> {
            New foo() {id = guid. Newguid(). Tostring(), field1 = "Zhang San", field2 = "option 1", field3 = datetime. Now. Addyears (- 6), field4 = "1918731555x", field5 = "No. 66... Street, Kunming City, Yunnan Province"},
            New foo() {id = guid. Newguid(). Tostring(), field1 = "Li Si", field2 = "option 2", field3 = datetime. Now. Addyears (- 7), field4 = "1918731556x", field5 = "No. 56... Street, Yuxi City, Yunnan Province"},
            New foo() {id = guid. Newguid(). Tostring(), field1 = "Wang Wu", field2 = "option 1", field3 = datetime. Now. Addyears (- 8), field4 = "1918731557x", field5 = "No. 46... Street, Honghe Prefecture, Yunnan Province"},
            New foo() {id = guid. Newguid(). Tostring(), field1 = "Zhao Liu", field2 = "option 3", field3 = datetime. Now. Addyears (- 9), field4 = "1918731558x", field5 = "No. 36... Street, Chuxiong Prefecture, Yunnan Province"},
        };

        this.Load += Form1_Load;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        bindingList = new BindingList<Foo>(foos);
        var source = new BindingSource(bindingList, null);
        //Control data binding
        dataGridView1.DataSource = source;

        textBox1.DataBindings.Add("Text", source, "Field1", true, DataSourceUpdateMode.OnPropertyChanged);
        comboBox1.DataBindings.Add("Text", source, "Field2", true, DataSourceUpdateMode.OnPropertyChanged);
        dateTimePicker1.DataBindings.Add("Value", source, "Field3", true, DataSourceUpdateMode.OnPropertyChanged);
        textBox2.DataBindings.Add("Text", source, "Field4", true, DataSourceUpdateMode.OnPropertyChanged);
        textBox3.DataBindings.Add("Text", source, "Field5", true, DataSourceUpdateMode.OnPropertyChanged);

        bindingList.AddingNew += BindingList_AddingNew;
    }

    private void BindingList_AddingNew(object sender, AddingNewEventArgs e)
    {
        e.NewObject = new Foo() { Id = Guid.NewGuid().ToString() };
    }

    //Preserve
    private void button1_Click(object sender, EventArgs e)
    {
        
    }

    //Add
    private void button2_Click(object sender, EventArgs e)
    {
        //Mode 1
        //bindingList.Add(new Foo() { Id = Guid.NewGuid().ToString() });
        //int selectIndex = dataGridView1.Rows.Count - 1;
        //dataGridView1.Rows[selectIndex].Selected = true;
        //dataGridView1.CurrentCell = dataGridView1.Rows[selectIndex].Cells[0];

        //Mode II
        var foo = bindingList.AddNew();
    }

    //Delete
    private void button3_Click(object sender, EventArgs e)
    {
        bindingList.RemoveAt(dataGridView1.CurrentRow.Index);
        dataGridView1.Rows[0].Selected = true;
        dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[0];
    }
}

class Foo
{
    public string Id { get; set; }
    public string Field1 { get; set; }
    public string Field2 { get; set; }
    public DateTime Field3 { get; set; }
    public string Field4 { get; set; }
    public string Field5 { get; set; }
}

The above is c# the details of synchronization of multiple controls in the same data source of WinForm. For more information about synchronization of multiple controls in the same data source of WinForm, please pay attention to other related articles of developeppaer!