Reputation: 1984
Am trying to search the student details with their name or email or mobile. For this I've three textboxes for Name, Email and Mobile.
And in my code I tried to get these details like,
DataObject entities=new DataObject();
foreach (DataObject.Student student in entities.students.Where(p =>
(p.FIRSTNAME+p.LASTNAME).Contains(txtName.Text)
|| p.MOBILE.Contains(txtMobile.Text)
|| p.EMAIL.Contains(txtEmail.Text))
{
//
}
and here, if I type sham
in the Email or in the Name textbox, its listing all the student details available in the database instead of listing only the student name or email contains sham
.
When I was debugging this, I tried giving the same valuesham,sham,sham
for name,mobile and email its listing perfectly, and also if I want to search by name that contains sham
, and If I type sham
in name, and anything else in the email and mobile, this also working perfectly....
One thing I came to know from this is, it expects all the parameter should have some value, I dunno why this expects like this, and I dunno how to fix this, can anyone help me here. Thanks in advance
Upvotes: 1
Views: 181
Reputation: 177163
Maybe, that every string "contains" an empty string, so if some of the textboxes are empty, some of the "OR" conditions will return true
for every student name and you get all students. Try to change the query to:
foreach (DataObject.Student student in entities.students.Where(p =>
((txtName.Text != string.Empty)
? (p.FIRSTNAME+p.LASTNAME).Contains(txtName.Text)
: false)
|| ((txtMobile.Text != string.Empty)
? p.MOBILE.Contains(txtMobile.Text)
: false)
|| ((txtEmail.Text != string.Empty)
? p.EMAIL.Contains(txtEmail.Text)
: false))
{
//
}
Instead of XXX.Text != string.Empty
you can also try string.IsNullOrEmpty(XXX.Text)
to catch the null
case as well. But I am not sure if LINQ to Entities will accept this method.
Edit
string.IsNullOrEmpty(XXX.Text)
works with LINQ to Entities, I've found a query in my own code that uses it without problems, so the better solution to check for empty string and for null
is:
foreach (DataObject.Student student in entities.students.Where(p =>
(!string.IsNullOrEmpty(txtName.Text)
? (p.FIRSTNAME+p.LASTNAME).Contains(txtName.Text)
: false)
|| (!string.IsNullOrEmpty(txtMobile.Text)
? p.MOBILE.Contains(txtMobile.Text)
: false)
|| (!string.IsNullOrEmpty(txtEmail.Text)
? p.EMAIL.Contains(txtEmail.Text)
: false))
{
//
}
Upvotes: 3