I must admit that I have known of Language Integrated Queries (LINQ) for some time now however I have never been in a position to use it. LINQ allows you to query data from any data source that supports LINQ such as SQL Server , XML , arrays, collections, and ADO.NET DataSets. There are three steps to executing a LINQ query, these are:
- Obtain your data source
- Create a query
- Execute the query
For the purpose of this tutorial I will be using a RadioButtonList class that represents a list control that encapsulates a group of radio button controls and the ListItem class which represents a data item in a data-bound list control.

Assume you want to provide some friendly advice to the individual who will be selecting the DMBS they wish to use. In this case should the end user select anything other than SQL Server 2008, I want to alert them they may want to re-think their selection.

Upon selecting the choice of SQL Server 2008 I alert the end user of my agreement.

To accomplish this first create a web form and paste the following code:
<h3>Pick the best DBMS:</h3> <asp:RadioButtonList runat="server" ID="ProductList" RepeatColumns="3" RepeatDirection="Vertical" AutoPostBack="true" OnSelectedIndexChanged="ProductListChanged"> <asp:ListItem Text="SQL Server 2008" Value="SQL Server 2008"></asp:ListItem> <asp:ListItem Text="Oracle 10g" Value="Oracle 11g"></asp:ListItem> <asp:ListItem Text="MySQL" Value="MySQL"></asp:ListItem> </asp:RadioButtonList> <asp:Label ID="lblChoice" runat="server" />
If you notice on the RadioButtonList I am performing a AutoPostBack and I have defined the OnSelectedIndexChanged method of ProductListChanged. The code for this method is:
/// <summary>
/// Fires the ProductList change event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void ProductListChanged(object sender, EventArgs e)
{
// Build the Linq query
var selected = from i in ProductList.Items.Cast<ListItem>()
where i.Selected == true
select i;
if (selected.ToList()[0].Text == "SQL Server 2008")
{
lblChoice.Text = "Great choice!";
}
else
{
lblChoice.Text = "You should rethink your decision!";
}
}
The method ProductListChanged builds up the LINQ query of the selected item which in turn allows me to use a if/else statement to alert the user. While this example is not complex it should get you to thinking about where and how you can employ LINQ in your work.
Build Your Own ASP.NET 3.5 Web Site Using C# & VB, 3rd Edition
Request Your Free Guidebook : This guide is packed full of practical examples, straightforward explanations, and ready-to-use code samples in both C# and VB. This comprehensive step-by-step guide will help get your database-driven ASP.NET web site up and running in no time.
Related posts:















Recent Comments