ADO.NET How To: Display to Display the Records of a Table in a Data Grid View



To display the records of a table in a data grid view, after getting a connection to the database, create a data adapter to which you can pass the expression to select the records and that specifies the connection. Create a data set. Fill the data set with the records from the data adapter. Assign the table from the data set to the data source of the data grid view. Here is an example:

// References needed: System.dll,
//                    System.Data,
//                    System.Drawing,
//                    System.Windows.Forms
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

public class DatabaseExercise : Form
    Button btnShow;
    DataGridView dgvProperties;

    public DatabaseExercise()

    private void InitializeComponent()
        btnShow = new Button();
        btnShow.Text = "Show";
        btnShow.Location = new System.Drawing.Point(12, 12);
        btnShow.Click += new EventHandler(btnShowClicked);
        dgvProperties = new DataGridView();
        dgvProperties.Location = new System.Drawing.Point(12, 44);
        dgvProperties.Anchor = AnchorStyles.Left | AnchorStyles.Top |
                               AnchorStyles.Right | AnchorStyles.Bottom;

        Text = "Database Exercise";
        StartPosition = FormStartPosition.CenterScreen;
        Size = new System.Drawing.Size(275, 235);


    private void btnShowClicked(object sender, EventArgs e)
        using (SqlConnection scnDepartmentStore =
                new SqlConnection("Data Source=(local);" +
                                  "Database='AltairRealtors1';" +
                                  "Integrated Security=yes;"))
            SqlDataAdapter sdaProperties = 
            		new SqlDataAdapter("SELECT * FROM dbo.Properties; ",
            new SqlDataAdapter();
            DataSet dsProperties = new DataSet("StoreItems");



            dgvProperties.DataSource = dsProperties.Tables[0];

public class Exercise
    public static int Main()
        Application.Run(new DatabaseExercise());
        return 0;


Home Copyright © 2010-2015 FunctionX