Display data in a Data Grid

After writing programs for 5 years, you have ever try to look at your first program when you start learning simple programs in Pascal or C++?? I wrote this simple program in early days of C# and ADO.NET.

In visual C#, the DataGrid is one of the ToolBox controls. DataGrid can be used to display data from a database by writing only few lines of code. In this article, I have used a database called "C:\\mcb.mdb" which has a table called 'Student'.

Create a Windows Application and add DataGrid to the Form

Add a DataGrid control to the form and set properties according to your needs.

data_g7.gif

Adding Source Code

Now you can add this few lines of code anywhere you want to load the data from the database. It may be mouse button click or the Form load event handler.

private void Form1_Load(object sender, System.EventArgs e)
{
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Student","Provider=Microsoft.JET.OLEDB.4.0;data source=C:\\mcb.mdb" );
DataSet ds = new DataSet();
da.Fill(ds, "Student");
dataGrid1.DataSource = ds.Tables["Student"].DefaultView ;
}

Simple. I create an OleDb DataAdapter and a DataSet object and call Fill method of data adapter, which fills the data set. After that I bind data set with the DataGrid using DataSource property. The contents of DataGrid looks like the following figure.

data_g6.jpg

How to Run?

  • Download the database zip files and unzip it.
  • Add using System.Data.OleDb; namespace in your project.
    Change the database path  in this string.  "Provider=Microsoft.JET.OLEDB.4.0;data source=C:\\mcb.mdb");
  • Run the application.

Up Next
    Ebook Download
    View all
    Learn
    View all