LINQ is a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. It extends C# and Visual Basic with native language syntax for queries and provides class libraries to take advantage of these capabilities. LINQ is great in improving the readability and maintainability of your code.


Our controls work flawlessly with LINQ and we plan to prepare a series of blog posts on utilizing LINQ when programming with RadControls for WinForms. Following last year’s Emulating Paging with RadGridView for WinForms and LINQ with 1 million records, now it is time to give you a quick overview of using RadComboBox for WinForms with LINQ.
A common scenario for our customers is to have two comboboxes on a form, where the selection in the first combobox determines the items in the second one. So, let’s have a form containing two RadComboBoxes:


Using RadComboBox for WinForms with LINQ

We can use the Load event to add a data source to our first combobox. To make our example more straight-forward, let’s say that the first combobox contains the names of all salespersons, working in a company. Once a person is chosen in the first combobox, the second combo will get updated with the client accounts this person is responsible for. In other words, the first combobox is used to filter client accounts.

Initially, you need to create a new server connection from the Server Explorer in Visual Studio and then you need to add your Link to SQL classes template from the context menu in the Solution Explorer:



You can then drag your tables on the just created designer surface and the corresponding classes will be generated for you. 

The next step is to query for all salespersons in say Form_Load event:

private void Form1_Load(object sender, EventArgs e) 
            context = new UsingRadComboboxWithLinqDataContext(); 
            this.salesPersonsComboBox.DisplayMember = "Name"
            this.salesPersonsComboBox.ValueMember = "ID"
            this.salesPersonsComboBox.DataSource = context.SalesPersons;            

When the selected value member of the first combobox is changed the second combobox is populated accordingly:

private void salesPersonsComboBox_SelectedValueChanged(object sender, EventArgs e) 
            context = new UsingRadComboboxWithLinqDataContext(); 
            var accounts = from account in context.ClientAccounts 
                           where account.SalespersonID == (int)this.salesPersonsComboBox.SelectedValue 
                           select account; 
            this.accountsComboBox.DisplayMember = "ClientName"
            this.accountsComboBox.ValueMember = "ID"
            this.accountsComboBox.DataSource = accounts; 

I hope this post covers the basics when working with LINQ and you can now start working and enjoying LINQ in WinForms as well!

I will greatly appreciate your comments. Do you folks use LINQ in your applications?  

Related Posts