Procedura: associare un oggetto DataView a un controllo DataGridView Windows FormHow to: Bind a DataView Object to a Windows Forms DataGridView Control

Il controllo DataGridView fornisce un sistema efficiente e flessibile per visualizzare i dati in formato tabulare.The DataGridView control provides a powerful and flexible way to display data in a tabular format. Il controllo DataGridView supporta il modello di associazione dati standard di Windows Form ed è quindi possibile associarlo a DataView e a varie altre origini dati.The DataGridView control supports the standard Windows Forms data binding model, so it will bind to DataView and a variety of other data sources. Nella maggior parte dei casi, tuttavia, l'associazione viene eseguita a un componente BindingSource, che gestisce i dettagli dell'interazione con l'origine dati.In most situations, however, you will bind to a BindingSource component that will manage the details of interacting with the data source.

Per ulteriori informazioni sul DataGridView di controllo, vedere Cenni preliminari sul controllo DataGridView.For more information about the DataGridView control, see DataGridView Control Overview.

Per connettere un controllo DataGridView a un oggetto DataViewTo connect a DataGridView control to a DataView

  1. Implementare un metodo per gestire i dettagli del recupero di dati da un database.Implement a method to handle the details of retrieving data from a database. Nell'esempio di codice seguente viene implementato un metodo GetData che inizializza un componente SqlDataAdapter e lo usa per compilare DataSet.The following code example implements a GetData method that initializes a SqlDataAdapter component and uses it to fill a DataSet. Assicurarsi di impostare la variabile connectionString su un valore appropriato per il database.Be sure to set the connectionString variable to a value that is appropriate for your database. Sarà necessario disporre di accesso a un server in cui sia installato il database SQL Server di esempio AdventureWorks.You will need access to a server with the AdventureWorks SQL Server sample database installed.

    private void GetData()
    {
        try
        {
            // Initialize the DataSet.
            dataSet = new DataSet();
            dataSet.Locale = CultureInfo.InvariantCulture;
    
            // Create the connection string for the AdventureWorks sample database.
            string connectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;"
                + "Integrated Security=true;";
    
            // Create the command strings for querying the Contact table.
            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.
            SqlCommandBuilder 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 = "Data Source=localhost;Initial Catalog=AdventureWorks;" _
                    & "Integrated Security=true;"
    
            ' 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. Nel gestore eventi Load del form associare il controllo DataGridView al componente BindingSource e chiamare il metodo GetData per recuperare i dati dal database.In the Load event handler of your form, bind the DataGridView control to the BindingSource component and call the GetData method to retrieve the data from the database. L'oggetto DataView viene creato da una query LINQ to DataSetLINQ to DataSet sull'oggetto DataTable Contact e viene quindi associato al componente BindingSource.The DataView is created from a LINQ to DataSetLINQ to DataSet query over the Contact DataTable and is then bound to the BindingSource component.

    private 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
    

Vedere ancheSee Also

Data binding e LINQ to DataSetData Binding and LINQ to DataSet