C#.NET Data Binding Basics

October 17th, 2007 by comment Alex

Binding data from windows controls to objects is easy in C#.NET.  Here is a basic introduction: 

Step one:

Create a class named Employee in C# and add a get property for each field you want to bind to a windows control.

public string getLastName {

      get { return mStrLastName; }

} 

Add a set property for any fields that you want two-way binding to occur. For example:

public string firstName {

      get { return mStrFirstName; }

      set { mStrFirstName = value; }

} 

Step two:

Add a form to your project and throw some controls on the form.  For this example, add a list box and a textbox. Also, create an array of objects that you want to bind to this list box.

arrayOfEmployees = new ArrayList();

arrayOfEmpoyees.Add(new Employee(”Doe”,”John”,”SoftwareEngineer”,”ServerTeam”));

arrayOfEmployees.Add(new Employee(”Smith”,”Jane”,”SoftwareEngieer”,”ClientTeam”));

Step three:

Bind the data from the object to the list box and textbox

listBoxLastName.DataSource = arrayOfEmployees;

listBoxLastName.DisplayMember = “getLastName”;

txtBoxForFirstName.DataBindings.Add(”Text”, arrayOfEmployees, “getFirstName”);

Step four:

Run the project and notice that the data is bound to the list box and the textbox. 

First, notice that the textbox is an example of two-way binding.  If a user changes the values in the textbox then the object is updated with a new first name.  To change this to one-way binding, just remove the set property from the object bound to the textbox.

Secondly, simple binding is done to controls like textboxes that only have one possible value.  Complex binding is done to controls like list boxes, that have multiple values to display at once. 

This example shows both simple and complex binding as well as one-way and two-way binding. More advanced data binding topics in C#.Net Visual Studio 2005 would cover the DataGridView class.

Cheers,

alex

Comments

3 Responses to “C#.NET Data Binding Basics”

  1. Sam says:


    You assign the DataSource member to an ArrayList(). Would this work for other data structures, such as a List?

    Why is DisplayMember set to a string containing the name of a property (”getLastName”)? Wouldn’t the “getLastName” return a string without the quotes around its name?

    I have never done this sort of thing (data binding), so I apologize for any misunderstandings! I am enjoying your posts.

  2. Dave says:


    I can’t get your code to work. Can you send it???

  3. alexmcferron says:


    Sorry for the delay in response. I didn’t notice these comments until yesterday. In the future I’ll watch more closely.

    Your datasource has to implement IList or IListSource. Of this genre, arraylist is your best bet as a newbie to .NET data binding.

    Also, I sent the code to Dave. If anyone else wants it, let me know.

    Cheers,
    alex

Got something to say?