您的位置:首页 > 其它

使用DataTable进行检索和排序示例

2006-11-18 15:10 501 查看
DataBind.aspx如下:


<form id="form1" runat="server">


<div>


<asp:Label ID="DisplayLabel" runat="server" Text="Label"></asp:Label></div>


</form>

DataBind.aspx.cs如下:


using System;


using System.Data;


using System.Configuration;


using System.Collections;


using System.Web;


using System.Web.Security;


using System.Web.UI;


using System.Web.UI.WebControls;


using System.Web.UI.WebControls.WebParts;


using System.Web.UI.HtmlControls;


using System.Data.SqlClient;




public partial class DataTableExample : System.Web.UI.Page




...{


protected void Page_Load(object sender, EventArgs e)




...{


string connStr = ConfigurationManager.ConnectionStrings["northwind"].ConnectionString;


SqlConnection conn = new SqlConnection(connStr);


conn.Open();


SqlDataAdapter da = new SqlDataAdapter("SELECT CustomerID, CompanyName, Country FROM Customers", conn);


DataTable dt = new DataTable();


da.Fill(dt);




// 定义筛选条件字符串和排序字符串


string strExpr = "country = 'usa'";


string strSort = "companyname desc";




// 获得经过筛选和排序后的数据


DataRow[] resultRows = dt.Select(strExpr, strSort);


// 显示经过筛选和排序后的数据


Display_Label(resultRows, DisplayLabel);




}




// 显示DataRow数组中的内容


public void Display_Label(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>";


}


}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: