I am new to C# programming and currently working on Windows Forms. Just want to gain some knowledge on 'DataBinding' but unsuccessful till now. I did an extensive research on Internet but couldn't understand what DataBinding is meant for and how does it work. What I have come to know is that we set the DataSource of any control and bind it to that source then the change in that source will be updated in that control and vice-versa. Right?
Now what I tried to do is I made the following form:
listBox1, listBox2, textBox, button
I want to add items in listBox1. As the items are added in listBox1 they get automatically updated in listBox2 and if any item is deleted from listBox2, the same gets deleted from listBox1.
I used a TextBox and a Button to add items to listBox1. I wrote the following unsuccessful code to add the items to listBox1 and to update listBox2 whenever listBox1 gets updated:
public partial class Form1 : Form
{
BindingSource bs=new BindingSource();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Add(textBoxItem.Text);
bs.DataSource = listBox1.Items;
listBox2.DataSource = bs;
}
}
When I insert the first item in listBox1, I get that item in listBox2 as well but no item gets added in listBox2 after that while the items are easily added to listBox2.
How can I achieve this task and if possible please provide the coding for when any item from listBox2 is deleted, it gets deleted from listBox1 as well. I will put a button to delete item from listBox2.
Thank you!