Visual C#

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 command that specifies the records to select…

1 min read44 words1 code sample

Introduction#

To present table data within a data grid view, begin by defining a command that specifies the desired records. Subsequently, initialize a data adapter and pair it with a data set to show the results.

C#
// 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()
    {
        InitializeComponent();
    }

    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);

        Controls.Add(btnShow);
        Controls.Add(dgvProperties);
    }

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

            scnDepartmentStore.Open();

            sdaProperties.Fill(dsProperties);

            dgvProperties.DataSource = dsProperties.Tables[0];
        }
    }
}

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

Home All rights reserved © 2010 C# Key