[C#][OleDB] Daten aus MSAccess in einem DataGridView darstellen

string sOleConnStr = string.Empty;
string sMDBFile = @"c:\Test.mdb";
string sUser = "user";
string sPassword = "password";
string sSQL = "SELECT * FROM table";

if (sMDBFile.Contains(".mdb"))
{
    sOleConnStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sMDBFile + ";User ID=" + sUser + ";Jet OLEDB:Database Password=" + sPassword;
}
else
    if (sMDBFile.Contains(".accdb"))
    {
        sOleConnStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sMDBFile + ";User ID=" + sUser + ";Jet OLEDB:Database Password=" + sPassword;
    }

if (string.IsNullOrEmpty(sOleConnStr))
{
    MessageBox.Show("Sie haben eine nicht unterstützte MS Access Datenbankdatei ausgewählt.", AssemblyInfo.AssemblyProduct, MessageBoxButtons.OK, MessageBoxIcon.Warning);
    return;
}

OleDbConnection olecon = null;
OleDbDataReader olereader = null;

try
{
    olecon = new OleDbConnection(sOleConnStr);
    olecon.Open();

    OleDbCommand cmd = new OleDbCommand(sSQL, olecon);
    olereader = cmd.ExecuteReader();

    BindingSource bSource = new BindingSource();
    bSource.DataSource = olereader;

    // Datagridview auf einem Formular zum anzeigen der Daten
    dgvData.DataSource = bSource;
}
catch (Exception eole)
{
    MessageBox.Show(eole.Message, AssemblyInfo.AssemblyProduct, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
    // aufräumen
    if (olereader != null) olereader.Close();
    if (olecon != null) olecon.Close();
}

[C#][ODBC] Daten aus einer Tabelle in einem DataGridView anzeigen

// dgvGrid == DataGridView auf dem Formular
private void btnOpen_Click(object sender, EventArgs e)
{
    OdbcConnection conn = null;
    OdbcDataReader reader = null;

    try
    {
        // Verbindung herstellen
        conn = new OdbcConnection(@"dsn=MyDSN;UID=user;PWD=password;");
        conn.Open();

        // SQL-Kommando abschicken
        OdbcCommand cmd = new OdbcCommand("SELECT Names FROM MyTable", conn);
        // Daten einlesen
        reader = cmd.ExecuteReader();

        // Bindingsource erstellen
        BindingSource bSource = new BindingSource();
        // Reader an Source binden
        bSource.DataSource = reader;

        // Source an DataGridView übergeben
        dgvData.DataSource = bSource;
    }
    catch (Exception)
    {
    }
    finally
    {
        // aufräumen
        if (reader != null) reader.Close();
        if (conn != null) conn.Close();
    }
}
  • Weiterführender Link: Link