共用方式為


逐步解說:以資料填入資料集

這個逐步解說會建立含有一張資料表的資料集,並在其中填入 Northwind 範例資料庫的 Customers 資料表中的資料。 呼叫 TableAdapter 的 Fill 方法,以填入資料集的資料。

在這個逐步解說期間,您將了解如何:

  • 建立新的 [Windows 應用程式]。

  • 使用資料來源組態精靈,建立和設定資料集。

  • 從 [資料來源] 視窗拖曳至表單,以建立資料繫結 DataGridView

必要條件

若要完成這個逐步解說,您將需要:

建立 Windows 應用程式

第一個步驟是建立 [Windows 應用程式]。

建立新的 Windows 專案

  1. 在 Visual Studio 中,從 [檔案] 功能表中建立新的 [專案]。

  2. 將專案命名為 DatasetWalkthrough。

  3. 選取 [Windows 應用程式],然後按一下 [確定]。 如需詳細資訊,請參閱使用 .NET Framework 開發用戶端應用程式

    隨即建立 [DatasetWalkthrough] 專案,並將它加入至 [方案總管]。

建立 NorthwindDataSet

此步驟使用 [資料來源組態精靈],根據 Northwind 範例資料庫中的 Customers 資料表建立資料集。 您必須具有 Northwind 範例資料庫的存取權,才能建立連接。 如需設定 Northwind 範例資料庫的詳細資訊,請參閱如何:安裝範例資料庫

建立資料集

  1. 按一下 [資料] 功能表上的 [顯示資料來源]。

  2. 在 [資料來源] 視窗中,按一下 [加入新資料來源] 啟動 [資料來源組態精靈]。

  3. 請選取 [選擇資料來源類型] 頁面上的 [資料庫],再按 [下一步]。

  4. 在 [選擇資料連接] 頁面上,執行下列其中一項:

    • 如果下拉式清單中有提供 Northwind 範例資料庫的資料連接,請選取這個資料連接。

      -或-

    • 選取 [新增連接],啟動 [新增/修改連接] 對話方塊。

  5. 如果資料庫需要密碼,請選取選項來加入敏感性資料,然後按一下 [下一步]。

  6. 在 [將連接字串儲存到應用程式組態檔] 頁面上按 [下一步]。

  7. 在 [選擇您的資料庫物件] 頁面上,展開 [資料表] 節點。

  8. 選取 [Customers] 資料表,然後按一下 [完成]。

    [NorthwindDataSet] 會加入專案中,且 Customers 資料表會出現在 [資料來源] 視窗中。

將控制項加入至表單

將項目從 [資料來源] 視窗拖曳至 Windows 應用程式中的表單,以建立資料繫結控制項。

建立繫結至 Customers 資料表的 DataGridView

檢查將資料填入資料集所產生的程式碼

將項目從 [資料來源] 視窗拖曳至表單,會自動加入正確的程式碼,將資料集填入 Form1_Load 事件處理常式。

將資料載入至資料集

  1. 在 [方案總管] 中選取 [Form1],然後按一下 [檢視程式碼] 按鈕。

  2. 檢查 Form1_Load 事件處理常式。 TableAdapter 的 Fill 方法會將資料填入資料集中。

    Private Sub Form1_Load() Handles MyBase.Load
    
        'TODO: This line of code loads data into the 'NorthwindDataSet1.Customers' table.
        'You can move, or remove it, as needed.
    
        Me.CustomersTableAdapter1.Fill(Me.NorthwindDataSet1.Customers)
    End Sub
    
    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'northwindDataSet1.Customers' table.
        // You can move, or remove it, as needed.
    
        this.customersTableAdapter1.Fill(this.northwindDataSet1.Customers);
    }
    
  3. 您可以將此程式碼選擇性地複製至需要填入資料集之應用程式的其他部分。

執行應用程式

若要執行應用程式

  • 按 F5 執行應用程式。

  • 資料集會填入資料,並顯示在 DataGridView 中。

後續步驟

根據應用程式的需求,在建立資料繫結表單後,可能會有幾個想要執行的步驟。 一些您可以加強這個逐步解說的部分包括:

請參閱

概念

ADO.NET DataSet

將 Windows Form 控制項繫結至 Visual Studio 中的資料

準備您的應用程式以接收資料

將資料擷取至您的應用程式中

將控制項繫結至 Visual Studio 中的資料

在您的應用程式中編輯資料

驗證資料

儲存資料

其他資源

資料逐步解說

Visual Studio 資料應用程式的概觀

連接至 Visual Studio 中的資料