Reputation: 2188
I have a datatable of user info. I am trying to perform a search that can be using last name, user's ID or user's role(s). I have a search textbox for name and ID and a search dropdown for user's role. Not all can be blank but any combincation can be used. I am using the following but don;t think it is right since it always returns the entire datatable:
dtUsers.CaseSensitive = false;
var results = dtUsers.AsEnumerable()
.Where(r => r.Field<String>("LASTNAME").Contains(tbName.Text.Trim())
|| r.Field<String>("USERID").Contains(tbUserID.Text.Trim())
|| r.Field<String>("USERROLELIST").Contains(ddlRoles.SelectedItem.Text));
dtUsers = results.CopyToDataTable();
What am I doing wrong? I also need to be able to do partial search on name and ID.
Upvotes: 4
Views: 983
Reputation: 223422
Modify your condition to check for empty string first (Use String.IsNullOrWhiteSpace
)
and then apply your filter like:
var results = dtUsers.AsEnumerable()
.Where(r =>(!String.IsNullOrWhiteSpace(tbName.Text) && r.Field<String>("LASTNAME").Contains(tbName.Text.Trim())
|| (!String.IsNullOrWhiteSpace(tbUserID.Text) &&r.Field<String>("USERID").Contains(tbUserID.Text.Trim())
|| r.Field<String>("USERROLELIST").Contains(ddlRoles.SelectedItem.Text));
Similarly you can do that with the last condition as well like:
(ddlRoles.SelectedItem != null &&
!String.IsNullOrWhiteSpace(ddlRoles.SelectedItem.Text) &&
r.Field<String>("USERROLELIST").Contains(ddlRoles.SelectedItem.Text)
Upvotes: 3