ComponentOne LiveLinq > Getting Started with LiveLinq > 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.
C# |
Copy Code
|
---|---|
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 = new IndexedCollection<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(new Contact() { Name = s }); } } public class Contact : 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 C1DataSource 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:
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.