显示结果
CustomerID | CompanyName | Country |
---|---|---|
WHITC | White Clover Markets | USA |
TRAIH | Trail's Head Gourmet Provisioners | USA |
THECR | The Cracker Box | USA |
THEBI | The Big Cheese | USA |
SPLIR | Split Rail Beer & Ale | USA |
SAVEA | Save-a-lot Markets | USA |
RATTC | Rattlesnake Canyon Grocery | USA |
OLDWO | Old World Delicatessen | USA |
LONEP | Lonesome Pine Restaurant | USA |
LETSS | Let's Stop N Shop | USA |
LAZYK | Lazy K Kountry Store | USA |
HUNGC | Hungry Coyote Import Store | USA |
GREAL | Great Lakes Food Market | USA |
源代码
<% @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 >