问题
My apologies if I'm missing something obvious here....
I'm trying to customize a method to create a RadComboBox filter that adjusts as a user types (based on a Telerik demo). I'm using a Business Logic layer to pull in my datasource, and then I'm trying to use linq to select the values for the combo box OnItemsRequested depending on which combo box has made the request. I'm trying to have set the parameters in the "where" clause based on which GridColumn filter is making the request.
Here's my code to fill the list:
private void list_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
{
((RadComboBox)o).DataTextField = this.DataField;
((RadComboBox)o).DataValueField = this.DataField;
var employees = from emp in EmployeeBL.GetAllEmployees()
where emp.(this.UniqueName).Contains(e.Text)
select emp;
((RadComboBox)o).DataSource = employees;
((RadComboBox)o).DataBind();
}
Do I need to cast the UniqueName as parameter in my Data Object (EmployeeDTO)?
Thanks.
UPDATE:: Thanks to feedback, I've had some success with populating the combobox list. However, I think I've still got a miscue in my linq statement. The list builds the first time around, however, when I try to do the "StartsWith" comparison, the page throws an error saying the datasource contains no datarows, even though I'm definitely typing a "findable" string.
Here's what I have now.
private void list_ItemsRequested(RadComboBox o, RadComboBoxItemsRequestedEventArgs e)
{
o.DataTextField = this.DataField;
o.DataValueField = this.DataField;
DataTable dt = EmployeeBL.GetAllEmployees().AsDataTable();
IEnumerable<DataRow> query =
from emp in dt.AsEnumerable()
where emp.Field<String>(this.UniqueName).StartsWith(e.Text)
select emp;
DataTable boundTable = query.CopyToDataTable<DataRow>();
o.DataSource = boundTable;
o.DataBind();
}
回答1:
There's not a built-in way. You have some choices:
- Use a Dynamic Linq query library like ScottGu's
- Use reflection to build an Expression from the property name
- Use a
switch
statement to select an expression from a known list of properties (easy to code, less dynamic) - Use the CopyToDataTable extension method to create a data table that does support string-based sorting/filtering through DataViews
回答2:
Are you trying to call the method named in this.UniqueName
on each employee, and see if the result contains the text? Is so, you can use reflection.
If you're certain that o
is a RadComboBox
, it might as well be passed in as such.
private void list_ItemsRequested(RadComboBox o, RadComboBoxItemsRequestedEventArgs e)
{
o.DataTextField = this.DataField;
o.DataValueField = this.DataField;
PropertyInfo property = typeof(EmployeeDTO).GetProperty(this.UniqueName);
var employees = from emp in EmployeeBL.GetAllEmployees()
where ((IQueryable<string>)(property.GetValue(emp))).Contains(e.Text)
select emp;
o.DataSource = employees;
o.DataBind();
}
来源:https://stackoverflow.com/questions/14716618/evaluate-column-name-in-linq-where-clause