C#:从访问数据库获取数据并将其显示在列表框中

时间:2017-10-30 15:55:19

标签: c# ms-access

namespace Database_Project_Part_2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void displayButton_Click(object sender, EventArgs e)
        {
            string connectString = "Provider=Microsoft.Jet.OLEDB.4.0;"
                                    + "Data Source=C:\\Users\\dell\\Desktop\\Auto.mdb";

            //Create an OleDbConnection object, 
            //and then pass in the ConnectionString to the constructor.
            OleDbConnection cn = new OleDbConnection(connectString);

            //Open the connection.
            cn.Open();

            //Use a variable to hold the SQL statement.
            string selectString = "SELECT Manufacturer , Model, Y3ear, 
            Tranmission, Engine_Type, Drive_Train FROM Automobile;";

            //Create an OleDbCommand object.
            //Notice that this line passes in the SQL statement and the 
            //OleDbConnection object
            OleDbCommand cmd = new OleDbCommand(selectString, cn);

            //Send the CommandText to the connection, and then build an 
            //OleDbDataReader.
            //Note: The OleDbDataReader is forward-only.
            OleDbDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                automobileListBox.Items.Add(selectString);
                //Console.WriteLine(reader[0].ToString());
            }

            reader.Close();
            cn.Close();

        }

        private void exitButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

我不知道为什么我会收到这个错误:

  

System.Data.OleDb.OleDbException:'没有给出一个或多个值   必要的参数。'在线: OleDbDataReader reader =   cmd.ExecuteReader();

因为所有语法都是正确的。 谢谢,

0 个答案:

没有答案