Question

I have a query that takes the first and last name from text boxes and I get a var. This works if I want to change the datasource but that does not help me much as it breaks a lot of code doing it that way. I would prefer to use .filter. How can I use .filter in this case? Note that the .filter = results does not function and the reason why is "Cannot implicitly convert type 'System.Linq.IQueryable' to 'string'

private void btnSrchInterests_Click(object sender, EventArgs e)
        {
            DataClasses1DataContext db = new DataClasses1DataContext();

            var results = from c in db.CaseSelectors
                          join i in db.Interests on c.CaseNumberKey equals i.CaseNumberKey
                          where i.First.Contains(txtFirst.Text) && i.Last.Contains(txtLast.Text)
                          select c;

            caseSelectorBindingSource.Filter = results;                              

        }
Was it helpful?

Solution

the results is currently a System.Linq.IQueryable and thus cannot be cast to a string, as expected by the property Filter.

If the type of db.CaseSelectors is a IList<String> you can do the following

caseSelectorBindingSource.Filter = results.Single()

note tht this execute the linq query and return only a single string (and the query can only return one item).

If the type of db.CaseSelectors is a IList<ComplexType> you can do the following

caseSelectorBindingSource.Filter = results.Single().YourFilterProperty;

Where YourFilterProperty is the property that contains the string with the filter

If your query returns a multiple items, you do a results.First() or iterate list to construct your filter.

Edit

After debating, the full answer is:

    private void btnSrchInterests_Click(object sender, EventArgs e)
    {
        DataClasses1DataContext db = new DataClasses1DataContext();

        var results = from c in db.CaseSelectors
                      join i in db.Interests on c.CaseNumberKey equals i.CaseNumberKey
                      where i.First.Contains(txtFirst.Text) && i.Last.Contains(txtLast.Text)
                      select c.CaseNumberKey;

        caseSelectorBindingSource.Filter = ("CaseNumberKey =" + String.Join(" OR CaseNumber = ", results.ToList()) );
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top