Basic LiveLinq Binding

Besides accelerating typical queries, LiveLinq also enables the use of LINQ in data binding scenarios.

To illustrate this, let us start with a simple example.

1.   Create a new WinForms project

2.   Add a reference to the C1.LiveLinq.dll assembly

3.   Add a button and a DataGridView to the main form

4.   Double-click the button and add this code to the form:

 

using C1.LiveLinq;

using C1.LiveLinq.AdoNet;

using C1.LiveLinq.LiveViews;

using C1.LiveLinq.Collections;

 

private void button1_Click(object sender, EventArgs e)

{

  // create data source

  var contacts = newIndexedCollection<Contact>();

 

  // bind list to grid (before adding elements)

  this.dataGridView1.DataSource =

    from c in contacts.AsLive()

    where c.Name.Contains("g")

    select c;

 

  // add elements to collection (after binding)

  var names = "Paul,Ringo,John,George,Robert,Jimmy,John Paul,Bonzo";

  foreach (string s in names.Split(','))

  {

    contacts.Add(newContact() { Name = s });

  }

}

 

public classContact : IndexableObject

{

  private string _name;

  public string Name

  {

    get { return _name; }

    set

    {

      OnPropertyChanging("Name");

      _name = value;

      OnPropertyChanged("Name");

    }

}

 

If you run the project and click the button, you should see two names on the grid: “Ringo” and “George”:



This may not seem surprising, since the data source is a query that returns all names that contain the letter “g”.

The interesting part is that all the contacts were added to the list after the query was assigned to the grid’s DataSource property. This shows that the LiveLinq query actually returned a live list, one that (a) notified the grid when elements were added to it, and (b) honored the where operator by showing only the names that contain “g”.

The differences between this LiveLinq query and a regular one are:

1.   The object collection is of type IndexedCollection<T>. This is a class provided by LiveLinq that supports the required change notifications.

2.   The Contact class is derived from a LiveLinq class IndexedObject so it can provide change notifications when its properties are set.

3.   The query itself contains an AsLive call that tells LiveLinq we want the result to remain active and issue change notifications that will be handled by bound controls.

You can test that the filter condition remains active by editing the grid and changing “Ringo” into “Ricky”. The row will be filtered out of the view as soon as you finish editing.

You can also check the effect of the AsLive call by commenting it out and running the sample again. This time, the grid will not receive any notifications as items are added to the list, and will remain empty.


Send us comments about this topic.
Copyright © GrapeCity, inc. All rights reserved.