1. 程式人生 > >C# ASP.NET 資料庫連線ACCESS2010

C# ASP.NET 資料庫連線ACCESS2010

連線access2010資料庫。

要新增名稱空間。,這裡旨在前面添加了一個gridview控制元件,來繫結資料,button控制元件沒有實際的作用。,.accdb資料庫放在E盤下。DataBase1資料庫中有一個表userinf

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;

namespace WebApplication2
{
    public partial class WebForm5 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            { DataBind(); }
        }
             void DataBind()
        {
            OleDbConnection conn = new 
             OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Database1.accdb");
            //這裡,   @是解決轉義字串或者把後面的\全部變為\\,如
            //OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\\Database1.accdb");
                 conn.Open();
            OleDbCommand cd = new OleDbCommand("select * from userinf where UClass='數媒一班' ", conn);
            OleDbDataReader dr = cd.ExecuteReader();
            GridView1.DataSource = dr;//設定datagrid控制元件資料來源
            GridView1.DataBind();//繫結到datagrid控制元件
            conn.Close();
        }

             protected void Button1_Click(object sender, EventArgs e)
             {

             }
        }
    }