상세 컨텐츠

본문 제목

Showing the data in a Datagrid from the database

C#

by xarfox 2011. 1. 5. 10:44

본문

The following set of code will show how to retrieve data from a database using DataGrid control.
*****************************************************************************************************

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()
{
InitializeComponent();
}
private void btnShow_Click(Object Sender,EventArgs e)
{
//filling the dataadapter with data(Student is only the nameofthe
//datagrid at runtime) using the dataset
da.Fill(ds,"Student");
}
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.


관련글 더보기