
<% @Import Namespace="System.Data" %>
<% @Import Namespace="System.Data.SqlClient" %>
<HTML>
	<HEAD>
		<title>使用DataTable进行检索和排序示例</title>
		<script language="C#" runat="server">

			void Page_Load(object sender, System.EventArgs e)
			{
				string ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];
				string Sql = "SELECT CustomerID, CompanyName, Country FROM Customers";

				SqlConnection thisConnection = new SqlConnection(ConnectionString);
				SqlDataAdapter adapter = new SqlDataAdapter(Sql, thisConnection);

				// 创建DataTable对象
				DataTable table = new DataTable();

				// 填充数据到DataTable
				adapter.Fill(table);

				// 定义筛选条件字符串和排序字符串
				string strExpr = "Country = 'USA'";
				string strSort = "CompanyName DESC";

				// 获得经过筛选和排序后的数据
				DataRow [] resultRows = table.Select(strExpr, strSort);

				// 显示经过筛选和排序后的数据
				DisplayRows(resultRows, DisplayLabel);
			}
			
			// 显示DataRow数组中的内容
			public void DisplayRows(DataRow [] rows, Label label)
			{
				// 检查返回数据是否为空
				if(rows.Length <= 0)
				{
					label.Text = "没有数据";
					return;
				}
				label.Text = "";

				// 遍历DataRow数组的行和列，显示数据
				label.Text += "<Table border='1'>";
				label.Text += "<TR><TH>CustomerID</TH><TH>CompanyName</TH><TH>Country</TH></TR>";
				foreach(DataRow row in rows)
				{
					label.Text += "<TR>";
					for(int i=0; i<row.Table.Columns.Count; i++)
					{
						label.Text += "<TD>";
						label.Text += row[i];
						label.Text += "</TD>";
					}
					label.Text += "</TR>";
				}
				label.Text += "</Table>";
			}

		</script>
	</HEAD>
	<body>
		<form id="Form1" method="post" runat="server">
			<H3>使用DataTable进行检索和排序示例</H3>
			<asp:Label id="DisplayLabel" runat="server">Label</asp:Label>
		</form>
	</body>
</HTML>
