如何:将 DataView 对象绑定到 Windows 窗体 DataGridView 控件

DataGridView 控件提供一种以表格格式显示数据的功能强大且灵活的方法。 DataGridView 控件支持标准 Windows 窗体数据绑定模型,因此它可以绑定到 DataView 和各种其他数据源。 但在多数情况下,该控件将会绑定到用于管理数据源交互详细信息的 BindingSource 组件。

有关 DataGridView 控件的详细信息,请参阅 DataGridView 控件概述

将 DataGridView 控件连接到 DataView

  1. 实现方法以处理有关从数据库检索数据的详细信息。 下面的代码示例实现 GetData 方法,该方法初始化 SqlDataAdapter 组件并使用该组件来填充 DataSet。 确保将 connectionString 变量设置为适合数据库的值。 您需要访问安装有 AdventureWorks SQL Server 示例数据库的服务器。

    void GetData()
    {
        try
        {
            // Initialize the DataSet.
            _dataSet = new DataSet
            {
                Locale = CultureInfo.InvariantCulture
            };
    
            // Create the connection string for the AdventureWorks sample database.
            const string connectionString = "...";
    
            // Create the command strings for querying the Contact table.
            const string contactSelectCommand = "SELECT ContactID, Title, FirstName, LastName, EmailAddress, Phone FROM Person.Contact";
    
            // Create the contacts data adapter.
            _contactsDataAdapter = new SqlDataAdapter(
                contactSelectCommand,
                connectionString);
    
            // Create a command builder to generate SQL update, insert, and
            // delete commands based on the contacts select command. These are used to
            // update the database.
            var contactsCommandBuilder = new SqlCommandBuilder(_contactsDataAdapter);
    
            // Fill the data set with the contact information.
            _contactsDataAdapter.Fill(_dataSet, "Contact");
        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    
    Private Sub GetData()
        Try
            ' Initialize the DataSet.
            dataSet = New DataSet()
            dataSet.Locale = CultureInfo.InvariantCulture
    
            ' Create the connection string for the AdventureWorks sample database.
            Dim connectionString As String = "..."
    
            ' Create the command strings for querying the Contact table.
            Dim contactSelectCommand As String = "SELECT ContactID, Title, FirstName, LastName, EmailAddress, Phone FROM Person.Contact"
    
            ' Create the contacts data adapter.
            contactsDataAdapter = New SqlDataAdapter( _
                contactSelectCommand, _
                connectionString)
    
            ' Create a command builder to generate SQL update, insert, and
            ' delete commands based on the contacts select command. These are used to
            ' update the database.
            Dim contactsCommandBuilder As SqlCommandBuilder = New SqlCommandBuilder(contactsDataAdapter)
    
            ' Fill the data set with the contact information.
            contactsDataAdapter.Fill(dataSet, "Contact")
    
        Catch ex As SqlException
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    
  2. 在窗体的 Load 事件处理程序中,将 DataGridView 控件绑定到 BindingSource 组件并调用 GetData 方法,以从数据库检索数据。 在 Contact DataTable 上从 LINQ to DataSet 查询创建 DataView,然后将其绑定到 BindingSource 组件。

    void Form1_Load(object sender, EventArgs e)
    {
        // Connect to the database and fill the DataSet.
        GetData();
    
        contactDataGridView.DataSource = contactBindingSource;
    
        // Create a LinqDataView from a LINQ to DataSet query and bind it
        // to the Windows forms control.
        EnumerableRowCollection<DataRow> contactQuery = from row in _dataSet.Tables["Contact"].AsEnumerable()
                                                        where row.Field<string>("EmailAddress") != null
                                                        orderby row.Field<string>("LastName")
                                                        select row;
    
        _contactView = contactQuery.AsDataView();
    
        // Bind the DataGridView to the BindingSource.
        contactBindingSource.DataSource = _contactView;
        contactDataGridView.AutoResizeColumns();
    }
    
    Private Sub Form1_Load(ByVal sender As System.Object, _
                           ByVal e As System.EventArgs) _
                           Handles MyBase.Load
        ' Connect to the database and fill the DataSet.
        GetData()
    
        contactDataGridView.DataSource = contactBindingSource
    
        ' Create a LinqDataView from a LINQ to DataSet query and bind it
        ' to the Windows Forms control.
        Dim contactQuery = _
            From row In dataSet.Tables("Contact").AsEnumerable() _
            Where row.Field(Of String)("EmailAddress") <> Nothing _
            Order By row.Field(Of String)("LastName") _
            Select row
    
        contactView = contactQuery.AsDataView()
    
        ' Bind the DataGridView to the BindingSource.
        contactBindingSource.DataSource = contactView
        contactDataGridView.AutoResizeColumns()
    End Sub
    

请参阅