Dynamic load where parameters for linqDatasource

Published on April 21, 2008

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 where param = new Parameter();
whereparam.Name = "BlogId";
whereparam.DefaultValue = BlogManager.CurrentBlogId.ToString();
whereparam.Type = TypeCode.Object;
linqDataSource.Where = "BlogId == <strong>Guid(@BlogId)</strong>";

You convert 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'_

\_**excerpt:** 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'\_