Connect Access database to C# application and display data in Datagridview

This article explains how to connect Access database to C# Windows Forms application. This is the Windows Form of the application:

Connect Access database to C# application

In Visual Studio Server Explorer, click Connect to database:

Connect Access database to C# application

Choose Microsoft Access Database file (OleDb) and click to continue:

Connect Access database to C# application

Browse to database file and click Ok:

Connect Access database to C# application
Now Database is connected to the application. Then we will display Data of the table"Employee" in Datagridview.

First create ConnectionString of the database to use it in code:

In Solution Explorer choose Settings:

Connect Access database to C# application
From Type select ConnectionString and name your connectionString and select Application from Scope then browse to the database file and click save:

Connect Access database to C# application
Now we start coding..

First add OleDb in Using and declare the database connection:

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; // Add this

namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
        OleDbConnection con = new OleDbConnection(WindowsFormsApplication4.Properties.Settings.Default.TestSetting);//this

        public Form1()
        {
            InitializeComponent();
        }

 Finally in display button add this code to display data in Datagridview:

private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (con.State != ConnectionState.Open)
                {
                    con.Open();
                }
                string selectCommand = "SELECT * FROM Employee";
                OleDbDataAdapter dataAdapter = new OleDbDataAdapter(selectCommand, con);
                OleDbCommandBuilder commandBuilder = new OleDbCommandBuilder(dataAdapter);
                DataTable table = new DataTable();
                dataAdapter.Fill(table);
                dataGridView1.DataSource=table;
                con.Close();
            }
            catch (OleDbException)
            {
                MessageBox.Show("");
            }

        }

Connect Access database to C# application and display data in Datagridview Connect Access database to C# application and display data in Datagridview Reviewed by Bloggeur DZ on 10:59 Rating: 5

Aucun commentaire:

Fourni par Blogger.