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 the 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 a 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.
  1. private void Form1_Load(object sender, System.EventArgs e) {  
  2.     OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Student""Provider=Microsoft.JET.OLEDB.4.0;data source=C:\\mcb.mdb");  
  3.     DataSet ds = new DataSet();  
  4.     da.Fill(ds, "Student");  
  5.     dataGrid1.DataSource = ds.Tables["Student"].DefaultView;  
Simple. I create an OleDb DataAdapter and a DataSet object and call the Fill method of data adapter, which fills the data set. After that, I bind the data set with the DataGrid using the DataSource property. The contents of DataGrid looks like the following figure.
 
data_g6.jpg
 
How to Run?
  • Download the database zip files and unzip them.
  • 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.


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.