Sunday, January 3, 2010

DataBindings

DataBindings can be found at your Properties list. It is mostly used, to create a connection between the text property of your control, and selected BindingSource, that is configured in advance.
Example: We have DataTable created in our DataSet. Let's say, this DataTable includes one DataColumn, which SQL statement is: SELECT COUNT(*) As NumberOfProducts FROM MySQLTable. Afterwards, we can connect NumberOfProducts to text property of our textBox, or label, using DataBindings.
This topic is huge — requires created tables, filled with data. So, I'm going to show you another powerful usage of DataBindings, right over your Form controls.

Our start position - new Form1 with 2 controls on it (textBox1 and label1). Our goal is to make label1 changing its text automatically according to text typed in textBox1. The old way of doing this, is to use TextChanged event of textBox1. But we are going use DataBindings. The only thing you need, is to add code mentioned below:

private void Form1_Load(object sender, EventArgs e)
{
label1.DataBindings.Add("Text", textBox1, "Text");
}

This code will create Binding using the specified control property name, data source, and data member, and adds it to the collection.

And this is the final effect. After the applications starts, text of label1 is clear, because the Binding was created. Every letter typed in textBox1 affects text property of label1. You can Add more Bindings, remove old ones, etc. For this purpose, it's more preferable as TextChanged event.

No comments:

Post a Comment