Web developers wiki ASP.NET Sitecore Sharepoint Kentico by Evident Interactive

Dynamic load whereparameters for linqDatasource

Modified: 2008/11/18 10:36 by Pieter Brinkman - Categorized as: ASP.NET, Csharp, Linq

When using an Linq Datasource (linq to sql) for a datagrid (Gridview, ListView, etc) you don't always want all rows from a table. To exclute data you can use the WhereParameters to add an where statement to your DataSource.

You can do limited where statements with the Visual Studio Wizards. When you need more than a limited statement you can dynamicly create an Parameter to add to your Linq DataSource.

The following examples shows how to filter the Linq Datasource that recovers all rows from the Post table and filters them on the BlogId. The BlogManager.CurrentBlogId gets the blog GUID from the Session.

   Parameter whereparam = new Parameter();
   whereparam.Name = "BlogId";
   whereparam.DefaultValue = BlogManager.CurrentBlogId.ToString();
   whereparam.Type = TypeCode.Object;
   linqDataSource.Where = "BlogId == Guid(@BlogId)"; 

You need to cast the @BlogId (string) to a Guid In the linqDataSource.Where property otherwise you get the following error:

Operator '==' incompatible with operand types 'Guid' and 'String' 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Web.Query.Dynamic.ParseException: Operator '==' incompatible with operand types 'Guid' and 'String'

Source: blog.newguid.net

 © Evident Interactive BV