我的项目有问题。我有保存类别的表格,我有listview
用于查看类别名称,我在listview
上方有一个文本框。当我在textbox
中键入字母时,我希望使用LINQ查询在列表视图中看到相应的类别名称,并且我正在使用此代码:
DataTable dt = (from c in Common.dc.TblBrands
where SqlMethods.Like(c.BrandName, txtSearch.Text+"%")
orderby c.BrandName
select c).getDataTable();
我可以正确看到名称,但是当我在textbox
输入品牌ID时,我希望看到品牌名称。我可以用什么查询来实现这个目标?
答案 0 :(得分:4)
您可以使用Contains或StartsWith。对于您的特定情况SqlMethods.Like(c.BrandName, txtSearch.Text+"%")
,您可以使用StartsWith
DataTable dt = (from c in Common.dc.TblBrands
where c.BrandName.StartsWith(txtSearch.Text)
orderby c.BrandName
select c).getDataTable();
答案 1 :(得分:1)
您还可以使用名称空间SqlMethods.Like
下的System.Data.Linq.SqlClient
。
DataTable dt = (from c in Common.dc.TblBrands
where SqlMethods.Like(c.BrandName, txtSearch.Text + "%")
orderby c.BrandName
select c).getDataTable();
已添加:如果您尝试搜索BrandId(假设int
类型),您可以这样做:
DataTable dt = (from c in Common.dc.TblBrands
where SqlMethods.Like(c.BrandName, txtSearch.Text + "%") ||
c.BrandId.ToString().Equals(txtSearch.Text)
orderby c.BrandName
select c).getDataTable();
答案 2 :(得分:1)
听起来你想要这样的东西:
DataTable dt = (from c in Common.dc.TblBrands
where SqlMethods.Like(c.BrandName, txtSearch.Text+"%")
|| c.BrandId == txtSearch.Text
orderby c.BrandName
select c).getDataTable();
或使用StartsWith
代替SqlMethods.Like
:
DataTable dt = (from c in Common.dc.TblBrands
where c.BrandName.StartsWith(txtSearch.Text)
|| c.BrandId == txtSearch.Text
orderby c.BrandName
select c).getDataTable();
当然,这都是假设BrandId
也是一个字符串。如果它是(比方说)一个整数,它可能会稍微发白。在这两种情况下,我首先亲自提取txtSearch.Text
- 我怀疑我甚至在代码中有查询可以访问UI,但这是一个架构问题。
(目前还不清楚getDataTable()
是什么 - 如果它是您自己的扩展方法,请考虑修改名称以遵循.NET约定。)