user5207499
user5207499

Reputation: 137

C# loading data from MS Access database to listbox

public partial class Form1 : Form
{
    OleDbCommand cmd = new OleDbCommand();
    OleDbConnection cn = new OleDbConnection();
    OleDbDataReader dr;
    public Form1()
    {
        InitializeComponent();

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        cn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AsusK450c\documents\visual studio 2010\Projects\ADD\ADD\testing.accdb;Persist Security Info=True";
        cmd.Connection = cn;
        loaddata();

    }
    private void loaddata()
    {
        listBox1.Items.Clear();
        listBox2.Items.Clear();
        try
        {
            string q = "select * from info";
            cmd.CommandText = q;
            cn.Open();
            dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    listBox1.Items.Add(dr[0].ToString());
                    listBox2.Items.Add(dr[1].ToString());
                }
            }
            dr.Close();
            cn.Close();

        }
        catch (Exception e)
        {
            cn.Close();
            MessageBox.Show(e.Message.ToString());
        }
    }
}

This is an image of the database: enter image description here

enter image description here

I added 2 list boxes. Those two should display the data i put in the database but It doesn't. I don't know which is wrong, the path, the code or the database

Upvotes: 0

Views: 1921

Answers (2)

Harutyun Imirzyan
Harutyun Imirzyan

Reputation: 464

I'm not sure what your problem is, but you can change the connectionString by this way:

System.Data.OleDb.OleDbConnectionStringBuilder builder = new System.Data.OleDb.OleDbConnectionStringBuilder();
            builder.Provider = "Microsoft.ACE.OLEDB.12.0";
            builder.OleDbServices = -1;
            builder.DataSource = @"C:\Users\AsusK450c\documents\visual studio 2010\Projects\ADD\ADD\testing.accdb";
            cn.ConnectionString = builder.ConnectionString;

OleDbServices = -1 can help you.

Upvotes: 0

Shamal Perera
Shamal Perera

Reputation: 1681

There is nothing wrong with you code. Check if you are getting any exceptions or pointed to the right database.

Also check if you have assigned the function Form1_Load() to form's load event

enter image description here

Upvotes: 1

Related Questions