Export (0) Print
Expand All

How to: Bind Data to the Windows Forms DataGridView Control

The DataGridView control supports the standard Windows Forms data binding model, so it will bind to a variety of data sources. In most circumstances, however, you will bind to a BindingSource component which will manage the details of interacting with the data source. The BindingSource component can represent any Windows Forms data source and gives you great flexibility when choosing or modifying the location of your data. For more information about the data sources supported by the DataGridView control, see DataGridView Control Overview (Windows Forms).

There is extensive support for this task in Visual Studio. For more information, see How to: Bind Data to the Windows Forms DataGridView Control Using the Designer and How to: Bind Data to the Windows Forms DataGridView Control Using the Designer and How to: Bind Data to the Windows Forms DataGridView Control Using the Designer and How to: Bind Data to the Windows Forms DataGridView Control Using the Designer and How to: Bind Data to the Windows Forms DataGridView Control Using the Designer.

To connect a DataGridView control to data

  1. Implement a method to handle the details of retrieving data from a database. The following code example implements a GetData method that initializes a SqlDataAdapter component and uses it to populate a DataTable. The DataTable is then bound to the BindingSource component. Be sure to set the connectionString variable to a value that is appropriate for your database. You will need access to a server with the Northwind SQL Server sample database installed.

    
    private:
        void GetData(String^ selectCommand)
        {
            try
            {
                // Specify a connection string. Replace the given value with a 
                // valid connection string for a Northwind SQL Server sample
                // database accessible to your system.
                String^ connectionString = 
                    "Integrated Security=SSPI;Persist Security Info=False;" +
                    "Initial Catalog=Northwind;Data Source=localhost";
    
                // Create a new data adapter based on the specified query.
                dataAdapter = gcnew SqlDataAdapter(selectCommand, connectionString);
    
                // Create a command builder to generate SQL update, insert, and
                // delete commands based on selectCommand. These are used to
                // update the database.
                gcnew SqlCommandBuilder(dataAdapter);
    
                // Populate a new data table and bind it to the BindingSource.
                DataTable^ table = gcnew DataTable();
                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.");
            }
        }
    
    
    
  2. In your form's Load event handler, bind the DataGridView control to the BindingSource component and call the GetData method to retrieve the data from the database.

    
    void Form1_Load(Object^ /*sender*/, System::EventArgs^ /*e*/)
    {
        // Bind the DataGridView to the BindingSource
        // and load the data from the database.
        dataGridView1->DataSource = bindingSource1;
        GetData("select * from Customers");
    }
    
    
    

The following complete code example provides buttons for reloading data from the database and submitting changes to the database.


#using <System.Data.dll>
#using <System.Transactions.dll>
#using <System.EnterpriseServices.dll>
#using <System.Xml.dll>
#using <System.Drawing.dll>
#using <System.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Data;
using namespace System::Data::SqlClient;
using namespace System::Windows::Forms;

public ref class Form1 : public System::Windows::Forms::Form
{
private:
    DataGridView^ dataGridView1;
private:
    BindingSource^ bindingSource1;
private:
    SqlDataAdapter^ dataAdapter;
private:
    Button^ reloadButton;
private:
    Button^ submitButton;

public:
    static void Main()
    {
        Application::Run(gcnew Form1());
    }

    // Initialize the form.
public:
    Form1()
    {
        dataGridView1 = gcnew DataGridView();
        bindingSource1 = gcnew BindingSource();
        dataAdapter = gcnew SqlDataAdapter();
        reloadButton = gcnew Button();
        submitButton = gcnew Button();

        dataGridView1->Dock = DockStyle::Fill;

        reloadButton->Text = "reload";
        submitButton->Text = "submit";
        reloadButton->Click += gcnew System::EventHandler(this,&Form1::reloadButton_Click);
        submitButton->Click += gcnew System::EventHandler(this,&Form1::submitButton_Click);

        FlowLayoutPanel^ panel = gcnew FlowLayoutPanel();
        panel->Dock = DockStyle::Top;
        panel->AutoSize = true;
        panel->Controls->AddRange(gcnew array<Control^> { reloadButton, submitButton });

        this->Controls->AddRange(gcnew array<Control^> { dataGridView1, panel });
        this->Load += gcnew System::EventHandler(this,&Form1::Form1_Load);
    }

    void Form1_Load(Object^ /*sender*/, System::EventArgs^ /*e*/)
    {
        // Bind the DataGridView to the BindingSource
        // and load the data from the database.
        dataGridView1->DataSource = bindingSource1;
        GetData("select * from Customers");
    }

    void reloadButton_Click(Object^ /*sender*/, System::EventArgs^ /*e*/)
    {
        // Reload the data from the database.
        GetData(dataAdapter->SelectCommand->CommandText);
    }

    void submitButton_Click(Object^ /*sender*/, System::EventArgs^ /*e*/)
    {
        // Update the database with the user's changes.
        dataAdapter->Update((DataTable^)bindingSource1->DataSource);
    }

private:
    void GetData(String^ selectCommand)
    {
        try
        {
            // Specify a connection string. Replace the given value with a 
            // valid connection string for a Northwind SQL Server sample
            // database accessible to your system.
            String^ connectionString = 
                "Integrated Security=SSPI;Persist Security Info=False;" +
                "Initial Catalog=Northwind;Data Source=localhost";

            // Create a new data adapter based on the specified query.
            dataAdapter = gcnew SqlDataAdapter(selectCommand, connectionString);

            // Create a command builder to generate SQL update, insert, and
            // delete commands based on selectCommand. These are used to
            // update the database.
            gcnew SqlCommandBuilder(dataAdapter);

            // Populate a new data table and bind it to the BindingSource.
            DataTable^ table = gcnew DataTable();
            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.");
        }
    }
};


This example requires:

  • References to the System, System.Windows.Forms, System.Data, and System.XML assemblies.

For information about building this example from the command line for Visual Basic or Visual C#, see Building from the Command Line (Visual Basic) or Command-line Building With csc.exe. You can also build this example in Visual Studio by pasting the code into a new project. For more information, see How to: Compile and Run a Complete Windows Forms Code Example Using Visual Studio and How to: Compile and Run a Complete Windows Forms Code Example Using Visual Studio and How to: Compile and Run a Complete Windows Forms Code Example Using Visual Studio and How to: Compile and Run a Complete Windows Forms Code Example Using Visual Studio and How to: Compile and Run a Complete Windows Forms Code Example Using Visual Studio.

Storing sensitive information, such as a password, within the connection string can affect the security of your application. Using Windows Authentication (also known as integrated security) is a more secure way to control access to a database. For more information, see Protecting Connection Information (ADO.NET).

Community Additions

ADD
Show:
© 2014 Microsoft