2014年6月10日 星期二
ASP.NET 使用DataSet+LINQ JOIN(關聯)資料表 (VB.NET語法)
參考資料1:聯結運算子 (LINQ to DataSet)
參考資料2:使用 Joins 以 LINQ 合併資料 (Visual Basic)
說明:本篇主要是參考「參考資料1」,來進行實作。
前置作業:
1.請準備好兩個資料表,分別為 學生(Student)、班級(Class);
學生資料表欄位只需要三個欄位,分別為班級編號(class_id)、學號(stud_id)、姓名(stud_name)。
班級資料表欄位只需要兩個欄位,分別為班級編號(class_id)、班級名稱(class_name)。
2.請在Html中放入一個GridView,之後抓出來的資料丟到GridView
Code如下
Imports System
Imports System.Linq
Imports System.Linq.Expressions
Imports System.Collections.Generic
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.Common
Imports System.Globalization
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim ds As DataSet = New DataSet
ds.Locale = CultureInfo.InvariantCulture
Dim connectionString As String = Nothing
connectionString = "Server=127.0.0.1;Database=test1;uid=test;pwd=test"
Using connection As SqlConnection = New SqlConnection(connectionString)
Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
"select st.class_id,st.stud_id,st.stud_name from Student as st where st.stud_id like '111%'", connection)
connection.Open()
adapter.Fill(ds, "student")
End Using
Using connection As SqlConnection = New SqlConnection(connectionString)
Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
"select cl.class_id,cl.class_name from class as cl", connection)
connection.Open()
adapter.Fill(ds, "class")
End Using
Dim stud_dt As DataTable = ds.Tables("student")
Dim class_dt As DataTable = ds.Tables("class")
Dim query = _
From st In stud_dt.AsEnumerable() _
Join cl In class_dt.AsEnumerable() _
On st.Field(Of String)("class_id") Equals _
cl.Field(Of String)("class_id") _
Select New With _
{ _
.class_id = st.Field(Of String)("class_id"), _
.class_name = cl.Field(Of String)("class_name"), _
.stud_id = st.Field(Of String)("stud_id"), _
.stud_name = st.Field(Of String)("stud_name") _
}
'可印出資料
'For Each strdata In query
' Response.Write(strdata.class_id & vbTab & _
' strdata.class_name & vbTab & _
' strdata.stud_id & vbTab & _
' strdata.stud_name)
'Next
GridView1.DataSource = query
GridView1.DataBind()
End If
End Sub
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言