/*--------------------------------------------------------------------------- USING ADO IN CODE STEP 1 Ron Kessler Created 4/22/2007 for C# 2005 --------------------------------------------------------------------------- This demonstrates the 7 steps to connect a datagrid control to an Access Database We create all the objects in code instead of using the controls from the toolbox THERE ARE MANY WAYS TO DO THIS...I AM SHOWING YOU THE SIMPLEST WAY HERE I changed the DB property to tell VS DO NOT COPY DB to output directory. -------------------------------------------------------------------------- */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.OleDb; //for Access If you use SQL then Import System.Data.SqlClient namespace ADO_MSAccess_In_Code { public partial class frmADO1 : Form { public frmADO1() { InitializeComponent(); } private void frmADO1_Load(object sender, EventArgs e) { loadMyGrid(); } private void loadMyGrid() { // ---define all the pieces and parts IN THIS ORDER!!! try { //---STEP 1: Connection String string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= ..\\..\\customers.mdb"; //STEP 2: CONNECTION OBJECT(uses the connString) OleDbConnection conn = new OleDbConnection(connString); //STEP 3 MAKE SQL STRING(to define which records to get) string sqlString = "SELECT * from Customers ORDER BY LastName"; //STEP 4 DATA ADAPTER (uses our SQL and Conn) OleDbDataAdapter dataAdapter =new OleDbDataAdapter(sqlString, conn); //STEP 5 DATASET(give the dataSet a name that relates to the data you want to display) DataSet dataSet = new DataSet(); //STEP 6 FILL THE DATA ADAPTER dataAdapter.Fill(dataSet, "customers"); //STEP 7 SET DATAGRID PROPERTIES DataGrid1.DataSource = dataSet; DataGrid1.DataMember = "customers"; } catch { MessageBox.Show("I could not read the database.", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Close(); } } } }