Reputation: 2020
I am making a search index. I got it working pretty good but I cannot incorporate ItemID (item numbers) in my search because i am having trouble converting the String in the TextBox.Text to a int in order for it to be a comparable type.
var q = (from t0 in db.Item
join t1 in db.Categories on t0.CategoryID equals t1.CategoryID
join t2 in db.Divisions on t0.DivisionID equals t2.DivisionID
where t0.DivisionID == DDLInt &&
//Contains
(t0.ItemName.Contains(txtSearch.Text.Trim()) ||
t0.Email.Contains(txtSearch.Text.Trim()) ||
t0.Description.Contains(txtSearch.Text.Trim()) ||
t0.Phone.Contains(txtSearch.Text.Trim()) ||
t0.ItemID.Equals(txtSearch.Text.Trim()))
// ^ This is the line where
// it breaks because it is not a comparable type
group t0 by new
{
I am not sure how to convert or parse it and still have the search work properly.
Upvotes: 0
Views: 1541
Reputation: 152634
Either parse the string
to an int
:
t0.ItemID.Equals(Convert.ToInt32(txtSearch.Text.Trim())))
or convert the int
to a string
:
t0.ItemID.ToString().Equals(txtSearch.Text.Trim()))
or take the conversion out of the query:
int searchID;
if !int.TryParse(txtSearch.Text.Trim(),out searchID)
searchID = -1; // set to an invalid ID
var q = (from t0 in db.Item
<snip>
t0.ItemID.Equals(searchID))
Upvotes: 3
Reputation: 148180
You can use int.Parse
t0.ItemName.Contains(txtSearch.Text.Trim())
would be
int.Parse(t0.ItemName.Contains(txtSearch.Text.Trim()))
Upvotes: 1
Reputation: 203829
If you are sure that it will be a valid integer you can use int.Parse
. If you are unsure if it's a valid integer you can use int.TryParse
and possibly prompt the user to re-enter if it's not valid.
It is generally best to validate all items before building the query (check that numbers are numbers, dates are dates, choice values are a valid choice, etc.). If something is invalid you can save yourself a database query by checking it at the start.
Upvotes: 1
Reputation: 13665
Should simply be:
t0.ItemID.Equals(int.Parse(txtSearch.Text.Trim()))
Upvotes: 1