Working with Data—Data Binding
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:Articles |
| Database Articles |
|
© 2006 Jeffery Suddeth |
Contents |
Data Binding
Window controls have the ability to bind their properties to the properties of other objects. When two properties are bound, a change in one is reflected in the other.
For example, consider the following listing for the Student class. The Student has two properties—the string value Name and the double value Gpa.
class Student { private string name; private double gpa; public string Name { get { return name; } set { name = value; } } public double Gpa { get { return gpa; } set { gpa = value; } } }
If we declare an instance of the Student as a member of a Windows Form, we can bind the Name and Gpa properties to the Text properties of a pair of TextBoxes.
// create the student student = new Student(); student.Name = "Jeff"; student.Gpa = 4.0; // bind the properties textBox1.DataBindings.Add(new Binding("Text", student, "Name")); textBox2.DataBindings.Add(new Binding("Text", student, "Gpa"));
We can also put a Button on the Form that displays the current values of the student’s Name and Gpa. This allows us to view the changes made to the object after we change the text in the TextBox.
private void testButton_Click(object sender, EventArgs e) { MessageBox.Show("Name: " + student.Name + " GPA: " + student.Gpa); }
Running the example, we can see that when the form first opens the initial values are displayed.
Figure 15.2
Then, we can change the text in the text boxes and click the
Test Button. The message box displays the values of the student object, which have been changed to the new values in theTextBoxes.
Figure 15.3
This type of data binding is called simple data binding. We can also bind a ListBox control to an array or collection of data. Binding to a collection of data is called complex data binding. To bind the ListBox to a collection you set the ListBox’s DataSource property. The ListBox will display the first public property of each item in the collection in its list. The next example binds an array of strings to a ListBox.
public partial class Form1 : Form { string[] names = { "Jeff", "Rachel", "Katy", "Evy", "Ben" }; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { listBox1.DataSource = names; } }
When the form is displayed, the names in the string array appear in the ListBox.
Figure 15.4
|




