如何:将数据绑定到 Windows 窗体 DataGridView 控件How to: Bind data to the Windows Forms DataGridView control

DataGridView 控件支持标准 Windows 窗体数据绑定模型,因此它可以绑定到各种数据源。The DataGridView control supports the standard Windows Forms data binding model, so it can bind to a variety of data sources. 通常,绑定到管理与数据源的交互的 BindingSourceUsually, you bind to a BindingSource that manages the interaction with the data source. BindingSource 可以是任何 Windows 窗体数据源,在选择或修改数据位置时,这为你提供了极大的灵活性。The BindingSource can be any Windows Forms data source, which gives you great flexibility when choosing or modifying your data's location. 有关 DataGridView 控件支持的数据源的详细信息,请参阅DataGridView 控件概述For more information about data sources the DataGridView control supports, see the DataGridView control overview.

Visual Studio 提供对 DataGridView 控件数据绑定的广泛支持。Visual Studio has extensive support for data binding to the DataGridView control. 有关详细信息,请参阅如何:使用设计器将数据绑定到 Windows 窗体 DataGridView 控件For more information, see How to: Bind data to the Windows Forms DataGridView control using the Designer.

将 DataGridView 控件连接到数据:To connect a DataGridView control to data:

  1. 实现方法以处理有关检索数据的详细信息。Implement a method to handle the details of retrieving the data. 下面的代码示例实现了一个初始化 SqlDataAdapterGetData 方法,并使用它来填充 DataTableThe following code example implements a GetData method that initializes a SqlDataAdapter, and uses it to populate a DataTable. 然后,它将 DataTable 绑定到 BindingSourceIt then binds the DataTable to the BindingSource.

  2. 在窗体的 Load 事件处理程序中,将 DataGridView 控件绑定到 BindingSource,并调用 GetData 方法检索数据。In the form's Load event handler, bind the DataGridView control to the BindingSource, and call the GetData method to retrieve the data.

示例Example

此完整的代码示例从数据库中检索数据,以在 Windows 窗体中填充 DataGridView 控件。This complete code example retrieves data from a database to populate a DataGridView control in a Windows form. 窗体还具有用于重新加载数据并将更改提交到数据库的按钮。The form also has buttons to reload data and submit changes to the database.

此示例需要:This example requires:

  • 访问 Northwind SQL Server 示例数据库。Access to a Northwind SQL Server sample database. 有关安装 Northwind 示例数据库的详细信息,请参阅获取用于 ADO.NET 代码示例的示例数据库For more information about installing the Northwind sample database, see Get the sample databases for ADO.NET code samples.

  • 对系统、System.web、System.web 和 System.web 程序集的引用。References to the System, System.Windows.Forms, System.Data, and System.Xml assemblies.

若要生成并运行此示例,请将代码粘贴到新 Windows 窗体项目中的Form1代码文件中。To build and run this example, paste the code into the Form1 code file in a new Windows Forms project. 有关从C#或 Visual Basic 命令行生成的信息,请参阅通过 csc 生成命令行从命令行生成For information about building from the C# or Visual Basic command line, see Command-line building with csc.exe or Build from the command line.

用 Northwind SQL Server 示例数据库连接的值填充示例中的 connectionString 变量。Populate the connectionString variable in the example with the values for your Northwind SQL Server sample database connection. Windows 身份验证(也称为集成安全性)是连接到数据库比在连接字符串中存储密码更为安全的方式。Windows Authentication, also called integrated security, is a more secure way to connect to the database than storing a password in the connection string. 有关连接安全的详细信息,请参阅保护连接信息For more information about connection security, see Protect connection information.

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

请参阅See also