Showing the data in a Datagrid from the database

Posted by Abhisek under C# category on | Views : 1894
In the code it is assumed that there is a table(Student) in MS Access database with two fields(sName & sRoll) containing some values or data.

Now design a form with a DataGrid control and a button(Show). Change the name of the button to btnShow.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;

namespace ShowData
public partial class Form1 : Form
Dataset ds;
OleDbCommand cmd;
OleDbConnection con;
OleDbDataAdapter da;
OleDbCommandBuilder cb;
public Form1()
private void btnShow_Click(Object Sender,EventArgs e)
//filling the dataadapter with data(Student is only the nameofthe
//datagrid at runtime) using the dataset
private void Form1_Load(Object Sender,EventArgs e)
con = new OleDbConnection("DataSource = d:\\Student.mdb;Provider = Microsoft.Jet.OleDb4.0");
cmd = new OleDbCommand("select*from student",con);
da = new OleDbDataAdapter();
da.SelectCommand = cmd;
cb = new OleDbCommandBuilder();
cb.DataAdapter = da;
ds = new Dataset();
//binding the datagrid to the dataset
this.dataGrid1.DataSource = ds;

We are using DataSet here which acts as a virtual table. The value is retrieved from the database and stores in the DataSet. Then we are passing this data to the DataGrid through DataSet.

Comments or Responses

Login to post response