using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;//tambahkan directive ini untuk OleDb
using System.IO; //digunakan untuk path
using System.Reflection; //digunakan untuk assembly
namespace DataGridView_OleDb_MsAccess
{
public partial class Form1 : Form
{
string mdfFilename;
string outputFolder;
string attachDbFilename;
string connString;
Boolean is_connecting;
OleDbConnection connection;
public Form1()
{
InitializeComponent();
this.LoadingData();
}
private void makeConnection()
{
Console.WriteLine("\\nBegin connecting...");
mdfFilename = "Database1.accdb";
outputFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
attachDbFilename = Path.Combine(outputFolder, mdfFilename);
connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + attachDbFilename;
connection = new OleDbConnection(connString);
//kalo menggunakan using block,
//maka koneksi akan otomatis closed pada akhir using block,
try
{
connection.Open();
Console.WriteLine("Connected..");
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
Console.WriteLine("ConnectionString: {0}", connection.ConnectionString);
is_connecting = true;
}
catch (Exception ex)
{
Console.WriteLine("Failed to Connect::" + ex.Message);
}
}
private void closeConnection()
{
if (is_connecting == true)
{
Console.WriteLine("\\nClosing connection...");
connection.Close();
}
}
private void LoadingData()
{
this.makeConnection();
Console.WriteLine("\\nBegin loading data...");
try
{
OleDbCommand command = new OleDbCommand("SELECT * FROM TablePerson", connection);
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
DataTable table = new DataTable();
adapter.Fill(table);
dataGridView1.DataSource = table;
Console.WriteLine("Success loading data...");
this.closeConnection();
}
catch (Exception ex)
{
Console.WriteLine("Failed to load data :: " + ex.Message);
}
}
}
}