简体   繁体   English

C#将数据从MS Access数据库加载到列表框

[英]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: 这是数据库的图像: 在此处输入图片说明

在此处输入图片说明

I added 2 list boxes. 我添加了2个列表框。 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 我不知道哪个是错误的,路径,代码或数据库

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 还要检查是否已将函数Form1_Load()分配给表单的加载事件

在此处输入图片说明

I'm not sure what your problem is, but you can change the connectionString by this way: 我不确定您的问题是什么,但是您可以通过以下方式更改connectionString:

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. OleDbServices = -1可以为您提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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