尝试使用Microsoft Access更新DataGridView时出错
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了尝试使用Microsoft 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 WORK7th SemesterVisual ProgrammingDatabase31.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();
}
}
}
答案
错误很明显,告诉您未分配连接字符串。因此,您应该为OleDbDataAdapter
分配连接字符串
var connectionString = @"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = F:UNI WORK7th SemesterVisual ProgrammingDatabase31.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();
}
以上是关于尝试使用Microsoft Access更新DataGridView时出错的主要内容,如果未能解决你的问题,请参考以下文章
使用传递查询中的数据更新 Microsoft Access 2013 表
使用 Exist 保留字 Microsoft Access 的两个更新查询
如何使用空字符串更新 Microsoft Access 数据库?