尝试使用Microsoft Access更新DataGridView时出错

时间:2017-12-25 17:14:32

标签: c# ms-access datagridview

我正在尝试使用Microsoft Access 2010在DataGridView中显示记录。但问题是每次我点击button1时都会收到错误消息“ConnectionString属性尚未初始化”

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Attendance_Generation_System
{
public partial class Take_attendance : Form
{
    OleDbConnection conn = new OleDbConnection();
    public Take_attendance()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        conn.ConnectionString=@"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = F:\UNI WORK\7th Semester\Visual Programming\Database31.accdb; " + "User id = admin; " + "Password = "; ;
        OleDbCommand cmd =new OleDbCommand("SELECT * FROM Attendancerecord");
        OleDbDataAdapter add = new OleDbDataAdapter(cmd);
        DataTable dt = new DataTable();
        add.Fill(dt);
        dataGridView1.DataSource=dt;
        cmd.ExecuteNonQuery();
    }
}

}

1 个答案:

答案 0 :(得分:0)

错误很明显,告诉您未分配连接字符串。因此,您应该为OleDbDataAdapter

分配连接字符串
var connectionString = @"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = F:\UNI WORK\7th Semester\Visual Programming\Database31.accdb; " + "User id = admin; " + "Password = ";
using (var oledbCnn = new OleDbConnection(connectionString))
{
    oledbCnn.Open();
    var cmd = new OleDbCommand("SELECT * FROM Attendancerecord", oledbCnn);
    OleDbDataAdapter add = new OleDbDataAdapter(cmd);
    DataTable dt = new DataTable();
    add.Fill(dt);
    dataGridView1.DataSource = dt;
    oledbCnn.Close();
}