SqlDataAdapter、DataSet 用法
以 VB.NET WinForm 來示範
Imports System.Data.SqlClientPublic Class Form1
Dim sCn As String = "data source =.\SQLexpress; attachDBfilename = |dataDirectory|ch16DB.mdf; integrated security = true; user instance = true;"
Dim ds As DataSet
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ds = New DataSet
FillInDataSet("成績單")
FillInDataSet("股票行情表")
FillInDataSet("員工")
FillInDataSet("書籍")
FillInDataSet("銀行帳戶")
For i = 0 To ds.Tables.Count - 1
cmbTables.Items.Add(ds.Tables(i).TableName)
Next
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Try
DataGridView1.DataSource = ds.Tables(cmbTables.SelectedItem.ToString)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Sub FillInDataSet(ByVal TableName As String)
Try
Dim cn As New SqlConnection(sCn)
Dim cm As New SqlCommand("select * from " & TableName, cn) '取全部的資料
Dim da As New SqlDataAdapter
da.SelectCommand = cm
da.Fill(ds, TableName)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class