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:
In Visual Studio Server Explorer, click Connect to database:
Choose Microsoft Access Database file (OleDb) and click to continue:
Browse to database file and click Ok:
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:
From Type select ConnectionString and name your connectionString and select Application from Scope then browse to the database file and click save:
Now we start coding..
First add OleDb in Using and declare the database connection:
In Visual Studio Server Explorer, click Connect to database:
Choose Microsoft Access Database file (OleDb) and click to continue:
Browse to database file and click Ok:
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:
From Type select ConnectionString and name your connectionString and select Application from Scope then browse to the database file and click save:
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
Reviewed by Bloggeur DZ
on
10:59
Rating:
Aucun commentaire: