Jitesh Byahut 8/10/2014 2353

How to Bind GridView From Microsoft Access

Here we are binding a GridView in Asp.Net from Microsoft Access. I create a table tblStudent in Access which is containing students information like Name, Branch and City. We are showing all records from Access in GridView.

Points Of Remember:

1. Add namespace System.Data and System.Data.OleDb in your C# page.

<!DOCTYPE html>

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>GridView with Access</title>

    <link href="../../Css/GridView.css" rel="stylesheet" />

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:GridView ID="GridView1" runat="server" CssClass="GridViewStyle" Width="710px">

            <HeaderStyle CssClass="HeaderStyle" />

            <RowStyle CssClass="RowStyle" />

            <AlternatingRowStyle CssClass="AlternatingRowStyle" />

        </asp:GridView>

    </div>

    </form>

</body>

</html>

In above example, I simply used a GridView.css for look and feel, for more about GridView cssClass visit GridView Style article.

C# Codes :

using System.Data;

using System.Data.OleDb;

 

public partial class GridView_test_GridView_Access : System.Web.UI.Page

{   

 

       OleDbConnection con=  new OleDbConnection(@"Provider=Microsoft.JET.OLEDB.4.0;
                       Data Source=E:\Asphelps Demo\DbStudent.mdb; Persist Security Info=False;"
);

 

    protected void Page_Load(object sender, EventArgs e)

    {

        BindGridView();

    }

    // Bind GridView

    protected void BindGridView()

    {

        DataTable dt = GetDataTable("select * from tblStudent");

        if (dt.Rows.Count > 0)

        {

            GridView1.DataSource = dt;

            GridView1.DataBind();

        }

    } 

    

    // Return records from Access

    public DataTable GetDataTable(string sql)

    {

        DataTable dt = new DataTable();

        OleDbDataAdapter da = new OleDbDataAdapter(sql, con);

        con.Open();

        da.Fill(dt);

        con.Close();

        return dt;

    }

}

If you want to bind access file from your application instead of local computer path then use below connection string.

// Bind Access connection string from your application
OleDbConnection
 con = new OleDbConnection(@"Provider=Microsoft.JET.OLEDB.4.0;Data Source="+HttpContext.Current.Server.MapPath(@"~\GridView\test\DbStudent.mdb")+"; Persist Security Info=False;");

Demo:



Please give your feedback for improving this page