Guide pratique pour lier des données au contrôle DataGridView Windows Forms

Le DataGridView contrôle prend en charge le modèle de liaison de données Windows Forms standard, afin qu’il puisse être lié à diverses sources de données. En règle générale, vous établissez une liaison à un BindingSource qui gère l’interaction avec la source de données. Il BindingSource peut s’agir de n’importe quelle source de données Windows Forms, ce qui vous offre une grande flexibilité lors du choix ou de la modification de l’emplacement de vos données. Pour plus d’informations sur les sources de données prises en charge par le DataGridView contrôle, consultez la vue d’ensemble du contrôle DataGridView.

Visual Studio prend en charge de manière étendue la liaison de données au contrôle DataGridView. Pour plus d’informations, consultez Guide pratique pour lier des données au contrôle DataGridView Windows Forms à l’aide du Concepteur.

Pour connecter un contrôle DataGridView aux données :

  1. Implémentez une méthode pour gérer les détails de la récupération des données. L’exemple de code suivant implémente une GetData méthode qui initialise un SqlDataAdapter, et l’utilise pour remplir un DataTable. Il lie ensuite le DataTableBindingSource.

  2. Dans le gestionnaire d’événements du Load formulaire, liez le DataGridView contrôle au BindingSourcecontrôle et appelez la GetData méthode pour récupérer les données.

Exemple

Cet exemple de code complet récupère les données d’une base de données pour remplir un contrôle DataGridView dans un formulaire Windows. Le formulaire comporte également des boutons pour recharger les données et envoyer des modifications à la base de données.

Cet exemple nécessite :

  • Accès à un exemple de base de données Northwind SQL Server. Pour plus d’informations sur l’installation de l’exemple de base de données Northwind, consultez Obtenir les exemples de bases de données pour ADO.NET exemples de code.

  • Références aux assemblys System, System.Windows.Forms, System.Data et System.Xml.

Pour générer et exécuter cet exemple, collez le code dans le fichier de code Form1 dans un nouveau projet Windows Forms. Pour plus d’informations sur la génération à partir de la ligne de commande C# ou Visual Basic, consultez la création de ligne de commande avec csc.exe ou Build à partir de la ligne de commande.

Remplissez la connectionString variable dans l’exemple avec les valeurs de votre exemple de connexion de base de données Northwind SQL Server. L’authentification Windows, également appelée sécurité intégrée, est un moyen plus sécurisé de se connecter à la base de données que de stocker un mot de passe dans le chaîne de connexion. Pour plus d’informations sur la sécurité des connexions, consultez Protéger les informations de connexion.

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

Voir aussi