Поделиться через


Практическое руководство. Связывание объекта DataView с элементом управления DataGridView в Windows Forms

Элемент управления DataGridView предоставляет мощный и гибкий способ отображения данных в табличном формате. Элемент управления DataGridView поддерживает стандартную модель привязки данных Windows Forms, поэтому он выполняет привязку к DataView и другим различным источникам данных. Однако в большинстве случаев выполняется привязка к компоненту BindingSource, управляющему взаимодействием с источником данных.

Дополнительные сведения об элементе DataGridView управления см. в разделе "Обзор элемента управления DataGridView".

Соединение элемента управления DataGridView с объектом DataView

  1. Реализуйте метод, обрабатывающий получение данных из базы данных. В следующем примере реализован метод GetData, инициализирующий компонент SqlDataAdapter и использующий его для заполнения объекта DataSet. Обязательно задайте для переменной connectionString значение, соответствующее вашей базе данных. Потребуется доступ к SQL Server с установленным образцом базы данных AdventureWorks.

    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 для получения данных из базы данных. Создается DataView из запроса LINQ to DataSet через контакт DataTable и затем привязан к компоненту 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
    

См. также