ado.net 学习 08 [DataView类 过滤-RowFilter属性]
1. DataView类,使用RowFilter属性严实在现这个功能。RowFilter属性和SQL查询中的Where子句功能类似。利用它可以使用逻辑操作符。
1 protected void Page_Load(object sender, EventArgs e) 2 { 3 // Create the Connection, DataAdapter, and DataSet. 4 string connectionString = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString; 5 SqlConnection con = new SqlConnection(connectionString); 6 string sql = "SELECT ProductID, ProductName, UnitsInStock, UnitsOnOrder, Discontinued FROM Products"; 7 8 SqlDataAdapter da = new SqlDataAdapter(sql, con); 9 DataSet ds = new DataSet(); 10 11 // Fill the DataSet 12 da.Fill(ds, "Products"); 13 14 // Filter for the Chocolade product. 15 DataView view1 = new DataView(ds.Tables["Products"]); 16 view1.RowFilter = "ProductName = 'Chocolade'"; 17 GridView1.DataSource = view1; 18 19 // Filter for products that aren't on order or in stock. 20 DataView view2 = new DataView(ds.Tables["Products"]); 21 view2.RowFilter = "UnitsInStock = 0 AND UnitsOnOrder = 0"; 22 GridView2.DataSource = view2; 23 24 // Filter for products starting with the letter P. 25 DataView view3 = new DataView(ds.Tables["Products"]); 26 view3.RowFilter = "ProductName LIKE 'P%'"; 27 GridView3.DataSource = view3; 28 29 // Bind all the data-bound controls on the page. 30 // Alternatively, you could call the DataBind() method 31 // of each grid separately 32 this.DataBind(); 33 }
前台代码:
1 <div> 2 Filter = <b>"ProductName = 'Chocolade' "</b> 3 <br /><br /> 4 <asp:GridView ID="GridView1" runat="server"> 5 </asp:GridView> 6 <br /> 7 Filter = <b>"UnitsInStock = 0 AND UnitsOnOrder = 0"</b> 8 <br /><br /> 9 <asp:GridView ID="GridView2" runat="server"> 10 </asp:GridView> 11 <br /> 12 Filter = <b>"ProductName LIKE 'P%'"</b> 13 <br /><br /> 14 <asp:GridView ID="GridView3" runat="server"> 15 </asp:GridView> 16 <br /> 17 </div>
运行结果: