Webform中linq to sql多条件查询(小练习)

时间:2023-03-08 21:11:29
Webform中linq to sql多条件查询(小练习)

多条件查询:逐条判断,从第一个条件开始判断,如果满足,取出放入集合,再从集合中查询第二个条件。。。

Webform中linq to sql多条件查询(小练习)

aspx代码

 <body>
<form id="form1" runat="server"> <br />
<asp:Label ID="Label1" runat="server" Text="关键字:"></asp:Label>
<asp:TextBox ID="Gjz" runat="server" Font-Size="12px"></asp:TextBox>
&nbsp;
<asp:Label ID="Label2" runat="server" Text="价格:"></asp:Label>
&nbsp;<asp:TextBox ID="price1" runat="server" Font-Size="12px" Width="52px"></asp:TextBox>
&nbsp;
<asp:Label ID="Label3" runat="server" Text="到"></asp:Label>
&nbsp;
<asp:TextBox ID="price2" runat="server" Font-Size="12px" Width="52px"></asp:TextBox>
&nbsp;
<asp:Button ID="select" runat="server" Text="查询" OnClick="select_Click" />
<br />
<br />
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table width="" border="" cellspacing="" cellpadding="" bgcolor="#6600FF">
<tr style="height:25px;">
<td width="" bgcolor="#FFFFFF">名称</td>
<td width="" bgcolor="#FFFFFF">上市时间</td>
<td width="" bgcolor="#FFFFFF">油耗</td>
<td width="" bgcolor="#FFFFFF">功率</td>
<td width="" bgcolor="#FFFFFF">价格</td>
</tr>
</HeaderTemplate> <ItemTemplate>
<tr style="height:25px;">
<td bgcolor="#FFFFFF"><%#Eval("Name") %></td>
<td bgcolor="#FFFFFF"><%#Eval("Time","{0:yyyy年MM月dd日}") %></td>
<td bgcolor="#FFFFFF"><%#Eval("Oil") %></td>
<td bgcolor="#FFFFFF"><%#Eval("Powers") %></td>
<td bgcolor="#FFFFFF"><%#Eval("Price") %></td>
</tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater>
</form>
</body>

 aspx.cs代码:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
coenctDataContext _conext = new coenctDataContext();
Repeater1.DataSource= _conext.Car;
Repeater1.DataBind();
}
} protected void select_Click(object sender, EventArgs e)
{
coenctDataContext _contest = new coenctDataContext(); List<Car> list = _contest.Car.ToList();
string key =Gjz.Text.ToString(); //判断第一个条件是否为空,如果为空不操作,去判断第二个条件看是否满足;不为空,继续 继续查询
if (key != "")
{
list = list.Where(p => p.Name.Contains(key)).ToList();
//关键字变原色,用foreach去查看集合中满足条件的字
foreach(Car data in list )
{
string s = data.Name.Replace(key, "<span style ='color:red;'>" + key + "</span>");
data.Name = s;
}
} //判断第二个条件
string mi = price1.Text;//取text判断是否为空
string ma = price2.Text;//取text判断是否为空 //先判断第二个条件中,文本框中是否为空
if(mi !="" && ma != "")
{
decimal min = Convert.ToDecimal(price1.Text);
decimal max = Convert.ToDecimal(price2.Text); list= list.Where(p=>p.Price.Value>=min && p.Price<=max).ToList(); } //指定数据源显示出来
Repeater1.DataSource = list;
Repeater1.DataBind(); }
}