使用linq在asp.net中使用多个控件搜索多个列

时间:2013-04-08 06:42:09

标签: c# asp.net sql-server linq linq-to-sql

Project_Detail pro = new Project_Detail();
string title=Ttitle.Text;
string year1=Tyear.Text;
string key = Tkeywrds.Text;
string area = Ddl_area.Text;
string categ = Ddl_catgry.Text;
string tech = Ddl_tech.Text;
string type =Ddl_type.Text;

var q = from obj in da.Project_Details
        where obj.Project_Title.Contains(title) 
              || obj.Submission_Date.Contains(year1) 
              || obj.Keywords.Contains(key) 
              || obj.Project_Area.Contains(area) 
              || obj.Project_Category.Contains(categ) 
              || obj.Project_Technology.Contains(tech) 
              || obj.Project_Type.Contains(type)
        select obj;

if (q != null)
{
    DetailsView1.DataSource = q;
    DetailsView1.DataBind();
}
else
{
    Literal1.Text = "Data not found";
}

此代码给出了表的最后记录,也没有给出条件结果。 我想要所有条件的结果,并且想要使用LIke satatement。

2 个答案:

答案 0 :(得分:1)

q永远不会为空。但它可能是空的。因此,您应该将代码更改为

if (q.Any()) // <<-----
{
    DetailsView1.DataSource = q;
    DetailsView1.DataBind();
}
else
{
    Literal1.Text = "Data not found";
}

答案 1 :(得分:0)

您还可以使用计数方法.Count()

if (q.count()>0)
{
    DetailsView1.DataSource = q;
    DetailsView1.DataBind();
}
else
{
    Literal1.Text = "Data not found";
}