如何:將資料系結至 Windows Forms DataGridView 控制項

控制項 DataGridView 支援標準 Windows Forms 資料系結模型,因此它可以系結至各種資料來源。 通常,您會系結至 BindingSource ,以管理與資料來源的互動。 BindingSource可以是任何 Windows Forms 資料來源,這可讓您在選擇或修改資料的位置時有極大的彈性。 如需控制項所支援之資料來源 DataGridView 的詳細資訊,請參閱 DataGridView 控制項概觀

Visual Studio 對 DataGridView 控制項的資料系結具有廣泛的支援。 如需詳細資訊,請參閱 如何:使用設計 工具將資料系結至 Windows Forms DataGridView 控制項。

若要將 DataGridView 控制項連線至資料:

  1. 實作 方法來處理擷取資料的詳細資料。 下列程式碼範例會實作 GetData 方法, SqlDataAdapter 初始化 ,並用它來填入 DataTable 。 然後,它會將 DataTable 系結至 BindingSource

  2. 在表單的事件處理常式中 Load ,將 DataGridView 控制項系結至 BindingSource ,並呼叫 GetData 方法來擷取資料。

範例

這個完整的程式碼範例會從資料庫擷取資料,以在 Windows 表單中填入 DataGridView 控制項。 表單也有按鈕可重載資料,並將變更提交至資料庫。

這個範例需要:

  • 存取 Northwind SQL Server 範例資料庫。 如需安裝 Northwind 範例資料庫的詳細資訊,請參閱 取得 ADO.NET 程式碼範例 的範例資料庫。

  • System、System.Windows.Forms、System.Data 和 System.Xml 元件的參考。

若要建置並執行此範例,請將程式碼貼到新的 Windows Forms 專案中的 Form1 程式碼檔案中。 如需從 C# 或 Visual Basic 命令列建置的相關資訊,請參閱 使用 csc.exe 建置命令列或 從命令列 建置。

connectionString使用 Northwind SQL Server 範例資料庫連線的值填入範例中的 變數。 Windows 驗證也稱為整合式安全性,是連線到資料庫比將密碼儲存在連接字串更安全的方式。 如需連線安全性的詳細資訊,請參閱 保護連線資訊

using System;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Windows.Forms;

namespace WindowsFormsApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    }
}
public class Form1 : Form
{
    private DataGridView dataGridView1 = new DataGridView();
    private BindingSource bindingSource1 = new BindingSource();
    private SqlDataAdapter dataAdapter = new SqlDataAdapter();
    private Button reloadButton = new Button();
    private Button submitButton = new Button();

    [STAThread()]
    public static void Main()
    {
        Application.Run(new Form1());
    }

    // Initialize the form.
    public Form1()
    {
        dataGridView1.Dock = DockStyle.Fill;

        reloadButton.Text = "Reload";
        submitButton.Text = "Submit";
        reloadButton.Click += new EventHandler(ReloadButton_Click);
        submitButton.Click += new EventHandler(SubmitButton_Click);

        FlowLayoutPanel panel = new FlowLayoutPanel
        {
            Dock = DockStyle.Top,
            AutoSize = true
        };
        panel.Controls.AddRange(new Control[] { reloadButton, submitButton });

        Controls.AddRange(new Control[] { dataGridView1, panel });
        Load += new EventHandler(Form1_Load);
        Text = "DataGridView data binding and updating demo";
    }

    private void GetData(string selectCommand)
    {
        try
        {
            // Specify a connection string.
            // Replace <SQL Server> with the SQL Server for your Northwind sample database.
            // Replace "Integrated Security=True" with user login information if necessary.
            String connectionString =
                "Data Source=<SQL Server>;Initial Catalog=Northwind;" +
                "Integrated Security=True";

            // Create a new data adapter based on the specified query.
            dataAdapter = new SqlDataAdapter(selectCommand, connectionString);

            // Create a command builder to generate SQL update, insert, and
            // delete commands based on selectCommand.
            SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

            // Populate a new data table and bind it to the BindingSource.
            DataTable table = new DataTable
            {
                Locale = CultureInfo.InvariantCulture
            };
            dataAdapter.Fill(table);
            bindingSource1.DataSource = table;

            // Resize the DataGridView columns to fit the newly loaded content.
            dataGridView1.AutoResizeColumns(
                DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
        }
        catch (SqlException)
        {
            MessageBox.Show("To run this example, replace the value of the " +
                "connectionString variable with a connection string that is " +
                "valid for your system.");
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // Bind the DataGridView to the BindingSource
        // and load the data from the database.
        dataGridView1.DataSource = bindingSource1;
        GetData("select * from Customers");
    }

    private void ReloadButton_Click(object sender, EventArgs e)
    {
        // Reload the data from the database.
        GetData(dataAdapter.SelectCommand.CommandText);
    }

    private void SubmitButton_Click(object sender, EventArgs e)
    {
        // Update the database with changes.
        dataAdapter.Update((DataTable)bindingSource1.DataSource);
    }
}
Imports System.Data.SqlClient
Imports System.Windows.Forms

Public Class Form1
    Inherits Form

    Private dataGridView1 As New DataGridView()
    Private bindingSource1 As New BindingSource()
    Private dataAdapter As New SqlDataAdapter()
    Private WithEvents ReloadButton As New Button()
    Private WithEvents SubmitButton As New Button()

    Public Shared Sub Main()
        Application.Run(New Form1())
    End Sub

    ' Initialize the form.
    Public Sub New()

        dataGridView1.Dock = DockStyle.Fill

        ReloadButton.Text = "Reload"
        SubmitButton.Text = "Submit"

        Dim panel As New FlowLayoutPanel With {
            .Dock = DockStyle.Top,
            .AutoSize = True
        }
        panel.Controls.AddRange(New Control() {ReloadButton, SubmitButton})

        Controls.AddRange(New Control() {dataGridView1, panel})
        Text = "DataGridView data binding and updating demo"

    End Sub

    Private Sub GetData(ByVal selectCommand As String)

        Try
            ' Specify a connection string.  
            ' Replace <SQL Server> with the SQL Server for your Northwind sample database.
            ' Replace "Integrated Security=True" with user login information if necessary.
            Dim connectionString As String =
                "Data Source=<SQL Server>;Initial Catalog=Northwind;" +
                "Integrated Security=True;"

            ' Create a new data adapter based on the specified query.
            dataAdapter = New SqlDataAdapter(selectCommand, connectionString)

            ' Create a command builder to generate SQL update, insert, and
            ' delete commands based on selectCommand. 
            Dim commandBuilder As New SqlCommandBuilder(dataAdapter)

            ' Populate a new data table and bind it to the BindingSource.
            Dim table As New DataTable With {
                .Locale = Globalization.CultureInfo.InvariantCulture
            }
            dataAdapter.Fill(table)
            bindingSource1.DataSource = table

            ' Resize the DataGridView columns to fit the newly loaded content.
            dataGridView1.AutoResizeColumns(
                DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader)

        Catch ex As SqlException
            MessageBox.Show("To run this example, replace the value of the " +
                "connectionString variable with a connection string that is " +
                "valid for your system.")
        End Try

    End Sub

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _
        Handles Me.Load

        ' Bind the DataGridView to the BindingSource
        ' and load the data from the database.
        dataGridView1.DataSource = bindingSource1
        GetData("select * from Customers")

    End Sub

    Private Sub ReloadButton_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles ReloadButton.Click

        ' Reload the data from the database.
        GetData(dataAdapter.SelectCommand.CommandText)

    End Sub

    Private Sub SubmitButton_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles SubmitButton.Click

        ' Update the database with changes.
        dataAdapter.Update(CType(bindingSource1.DataSource, DataTable))

    End Sub

End Class

另請參閱