2014年6月9日 星期一

ASP.NET 兩個DataSet合併到另一個DataSet,並JOIN(關聯)DataSet中的資料(VB.NET語法)


參考資料1:瀏覽 DataRelation (ADO.NET)

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Dim connectionString As String = Nothing

            Dim n1 As DataSet = Nothing
            n1 = New DataSet("newtable")

            Dim stud As DataSet = Nothing, cl As DataSet = 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.班級編號,st.學號,st.姓名 from 學生 as st where st.學號 like '111%'", connection)

                connection.Open()
                stud = New DataSet()
                adapter.Fill(stud, "student")

            End Using

            n1.Merge(stud.Tables(0))

            Using connection As SqlConnection = New SqlConnection( _
connectionString)

                Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
                  "select cl.班級編號,cl.班級名稱 from 班級 as cl", connection)

                connection.Open()
                cl = New DataSet()
                adapter.Fill(cl, "class")

            End Using

            n1.Merge(cl.Tables(0))

            '第四個參數 預設為True代表使用條件約束
            Dim StudClassRelation As DataRelation = n1.Relations.Add("StudClass", n1.Tables("student").Columns("班級編號"), n1.Tables("class").Columns("班級編號"), False)

            Dim studRow, classRow As DataRow

            For Each studRow In n1.Tables("student").Rows
                Response.Write("st.班級編號:" & studRow("班級編號").ToString() & " st.學號:" & studRow("學號").ToString())
                For Each classRow In studRow.GetChildRows(StudClassRelation)
                    Response.Write(" cl.班級編號:" & classRow("班級編號").ToString() & " cl.班級名稱:" & classRow("班級名稱").ToString() & "<br/>")
                Next
            Next
        End If
    End Sub

沒有留言:

張貼留言