Thursday, April 7, 2011

Generating Dynamic query for LinqDataSource (Where clause) in code behind

Consider this scenario.

I have a GridView which is binded to a LinqDataSource and it binds the data on the Page_Load Event. Now I have a Search Box, where you would enter the text to be searched in the GridView. The value entered into the search box is searched across x number of columns in the Database table to find a match.

Initially what I did was to generate a new query within the click event handler of the search Button. But when I tried to delete the record after search, it gave me an error:

The GridView 'grdView' fired event RowDeleting which wasn't handled

Apparently this GridView is Binded to the LinqDataSource and upon binding it to a different datasource from Code Behind, there is some data corruption from the results not being properly fetched.

Instead of going further and digging into a solution, I thought about having the where clauses applied for the LinqDataSource right in code behind. Upon doing some research and getting ideas from this blog, I implemented it into my code:


LinqDataSourceSearch.Where = "name.Contains(\"" + txtSearchSponsor.Text.Trim() + "\")";


Pretty easy enough. Right?