views:

504

answers:

3

I am trying to write a textbox that will search on 5 DB columns and will return every result of a given search, ex. "Red" would return: red ball, Red Williams, etc. Any examples or similar things people have tried. My example code for the search.

Thanks.

    ItemMasterDataContext db = new ItemMasterDataContext();

    string s = txtSearch.Text.Trim();
    var q = from p in db.ITMSTs
            where p.IMITD1.Contains(s) ||
             p.IMITD2.Contains(s) ||
             p.IMMFNO.Contains(s) ||
             p.IMITNO.Contains(s) ||
             p.IMVNNO.Contains(s)
            select p;

    lv.DataSource = q;
    lv.DataBind();
+1  A: 

"q" in your example will be an IQueryable<ITMST>. I don't think the Datasource property of WebControl know what to do with that. try writing that line as:

 lv.DataSource = q.ToList();
James Curran
Unless I'm mistaken, web-binding is happy with IEnumerable<T>, which includes IQueryable<T> - so it should be happy. Winform binding would need the ToList(), though.
Marc Gravell
A: 

What you have is generally what people would do using linq. If you wanted to get more complex and use database wild cards then take a look at the SqlMethods class in System.Data.Linq.

@ James Curran You can assign the DataSource property q and it will work fine. The only different is when the query gets executed.

dfowler
A: 

You can do something like this (syntax may be off )

using(var db = new ItemMasterDataContext())
{
    var s = txtSearch.Text.Trim();
    var result = from p in db.ITMSTs select p;

    if( result.Any(p=>p.IMITD1.Contains(s))
         lv.DataSource = result.Where(p=>p.IMITD1.Contains(s))
    else if ( result.Any(p=>p.IMITD2.Contains(s))
        lv.DataSource = result.Where(p=>p.IMITD1.Contains(s))

    lv.DataBind();
}

or you might want to use this Link or this Link from MSDN.

Happy Coding!!

Perpetualcoder