简体   繁体   中英

Error when trying to update DataGridView using Microsoft Access

I am trying to show records in a DataGridView using Microsoft Access 2010. But the problem is each time i click on the button1 i get an error saying "The ConnectionString property has not been initialized"

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();
    }
}

}

The error is clear that tells you the connection string is not assigned. So, you should assign the connection string for 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM