dotnetmonitor.com

 
Index
Previous
Next

 

Simple binding is a general way to bind a property on a user interface element (Control) to a property on an instance of a type (object). For example, if a developer had an instance of a Customer type they could bind the Customer Name property to the Text property of a TextBox. When binding these two properties, changes to the TextBox.Text property will be propagated to the Customer.Name property and changes to the Customer.Name property will be propagated to the TextBox.Text property. Windows Forms simple binding supports binding to any public or internal .NET Framework property.

Sample: Simple Binding to a Business Object (VS 2005) (VS Project: DataBinding Intro)

/*******************************************************************

* Setup (using the Visual Studio Form designer):

*

* Add 3 TextBoxes to the Form (textBox1, textBox2 and textBox3)

* Add the code below to the Form.Load event

******************************************************************/

/*******************************************************************

* Create a customer instance (use the Customer type below)

******************************************************************/

Customer cust = new Customer(0, "Mr. Zero", 10.0M);

 

/*******************************************************************

* Bind textBox1, textBox2 and textBox3

******************************************************************/

this.textBox1.DataBindings.Add("Text", cust, "ID", true);

this.textBox2.DataBindings.Add("Text", cust, "Name", true);

this.textBox2.DataBindings.Add("Text", cust, "Rate", true);

 

Customer Business Object (VS 2005):

/*******************************************************************

* Setup (using the Visual Studio Form designer):

*

* Add a new C# Class file to your project and name it Customer.cs

* Replace the automatically generated Customer class with the

* following Customer class.

******************************************************************/

 

public class Customer

{

/* Private variables */

private int _id;

private string _name;

private Decimal _rate;

 

/* Constructor */

public Customer()

{

this.ID = -1;

this.Name = string.Empty;

this.Rate = 0.0M;

}

 

public Customer(int id, string name, Decimal rate)

{

this.ID = id;

this.Name = name;

this.Rate = rate;

}

 

/* Public API */

public int ID

{

get { return _id; }

set { _id = value; }

}

 

public string Name

{

get { return _name; }

set { _name = value; }

}

 

public Decimal Rate

{

get { return _rate; }

set { _rate = value; }

}

}

Complex Binding
Using Simple Binding with a List
Sample: Simple Binding to a List (VS 2005) (VS Project: DataBinding Intro)
Type Conversion
Formatting