2014年6月9日 星期一

ASP.NET 兩個DataSet合併到另一個DataSet,並Select DataSet中的某一筆資料(VB.NET語法)

說明:先下SQL指令,分別Select兩個不同的資料庫-資料表,並將資料合併在同一個DataSet,且針對DataSet Select某一筆資料。

參考資料1:DataSet.Merge 方法 (DataTable)
參考資料2:DataTable.Select Method (String)


    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 '將資料合併在這個DataSet
            n1 = New DataSet("newtable")
            Dim student1 As DataSet = Nothing, student2 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 班級,學號,姓名 from Student where 學號 like '400%'", connection)

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

            End Using
            n1.Merge(student1.Tables(0))

            connectionString = "Server=127.0.0.1;Database=test2;uid=test;pwd=test"
            Using connection As SqlConnection = New SqlConnection( _
   connectionString)

                Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
                  "select 班級,學號,姓名 from Student where 學號 like '899%'", connection)

                connection.Open()
                student2 = New DataSet()
                adapter.Fill(student2, "student1") '這裡的student1如果更改成student2,合併後n1.Tables(0)只能看到student1的資料,而n1.Tables(1)才會看到student2的資料

            End Using
            n1.Merge(student2.Tables(0))

            GridView1.DataSource = n1.Tables(0)
            GridView1.DataBind()

            Dim expression As String
            expression = "stud_no = '89906141'" '要搜尋的條件
            Dim foundRows() As DataRow = Nothing

            foundRows = n1.Tables(0).Select(expression) '使用Select搜尋資料

            Dim i As Integer
            For i = 0 To foundRows.GetUpperBound(0)
                For j = 0 To foundRows(i).ItemArray.Count - 1
                    If j = foundRows(i).ItemArray.Count - 1 Then
                        Label1.Text = Label1.Text & foundRows(i)(j)
                    Else
                        Label1.Text = Label1.Text & foundRows(i)(j) & ","
                    End If
                Next
            Next
        End If
    End Sub

沒有留言:

張貼留言