1. 程式人生 > 實用技巧 >ASP.net技巧:DataList、Gridview主從表明細顯示

ASP.net技巧:DataList、Gridview主從表明細顯示

http://yeziwenwen.blog.51cto.com/872759/188602
圖1.使用DataList顯示主從表明細
圖2.使用Gridview顯示主從表明細 資料庫為SQL Server例項資料庫Northwind,實現按照訂單編號,統計顯示出訂單詳情。 一構建Northwind庫中Orders訂單表以及Order Details訂單詳細表在DataSet中的表關係: InBlock.gifpublic class DataAccess
{
public DataSet Tablerelation()
InBlock.gif{
InBlock.gifstring strCon = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"
].ConnectionString;
InBlock.gif
InBlock.gif//構建連線
InBlock.gifSqlConnection con = new SqlConnection(strCon);
InBlock.gif
InBlock.gif//多個表來源於相同資料庫我們可以講sql語句一起書寫,但需要注意的是,必須在語句間用空格隔開
InBlock.gifSqlDataAdapter da = new SqlDataAdapter("select* from ordersselect * from [order details]",con);
InBlock.gifDataSet ds = new DataSet();
InBlock.gifda.Fill(ds);
InBlock.gif
InBlock.gif//我們也可以修改預設生成的(Table、Table1、……)表名
InBlock.gifds.Tables [0].TableName="orders"
;
InBlock.gifds.Tables[1].TableName = "orderDetails";
InBlock.gif
InBlock.gif//找到兩個表中相關聯的列
InBlock.gifDataColumn father = ds.Tables["orders"].Columns["OrderID"];
InBlock.gifDataColumn son = ds.Tables["orderDetails"].Columns["OrderID"];
InBlock.gif
InBlock.gif//給兩個列,建立名為tablerelation的關係
InBlock.gifDataRelation r = new DataRelation("tablerelation"
, father, son);
InBlock.gif
InBlock.gif//將表關係新增到資料集中
InBlock.gifds.Relations.Add(r);
InBlock.gifreturn ds;
InBlock.gif}
}