Visual Studio .NET - search on linq datasource not working correctly

Asked By Developer Buddy on 22-Dec-08 05:00 AM

Hello experts,

I have a LinqDataSource bound to ASp.Net GridView which simple displays a table's data in the grid. I have a search button and its code behind like this:

protected void search_Click(object sender, EventArgs e)

{

if (textOrderNumber.Text.Trim() != "")

{

      LinqDataSourceOrders.Where = "OrderNumber = " + textOrderNumber.Text;

}

}


This works fine most of the times and it filters the Orders based on order number entered in the text box.  The problem is: Sometimes, you have to click search button twice to see the results!  My code is really simple and thats all it does what I told you here. 

First time you press search, nothing shows! Second time you press search, the related rows appear in the grid!

I am using designer to bind the LinqDataSource to the GridView ... and its simple binding with all default values.

Any ideas what could be wrong? Or how would you do this type of filtering?

Thanks

re - Web Star replied to Developer Buddy on 22-Dec-08 05:16 AM

 

Your intuition serves you well. :)

The IEnumerable.Where extension method is fairly simple, and just yields an enumerator the filtered results based on the predicate you pass into it.  You *could* write a different variant of Where which understood how to query its input for search hints, or indeed did something more complex, as LINQ to SQL does.

Wes Dyer, one of the C# developers, has a video which shows how LINQ works (including a sketch of the Where method around 27:30

re - Web Star replied to Developer Buddy on 22-Dec-08 06:29 AM

If using EF, you can use esql string predicates like so and get sql
operators such as like, and, or, etc.

private void button6_Click(object sender, EventArgs e)
{
var u = Search("it.Tag like '%illiam' and it.IsLocal=true");
ObjectDumper.Write(u);

var u2 = Search("it.UserID=1");
ObjectDumper.Write(u2);
}

private IEnumerable<Test.Users> Search(string predicate)
{
using (Test.TestDB db = new Test.TestDB())
{
var q = db.Users.Where(predicate).Select(u => u);
return q.ToList();
}
}

If using L2S, you can download dynamic library:
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

re - Developer Buddy replied to Web Star on 22-Dec-08 10:13 AM

Thanks for replying.

What exactly you meant? How does this solve my problem?

Just a note to say, my code is working ... its just that sometimes I have to click twice to get the results appear!

Thanks