将Access数据库中的数据读入列表框

时间:2012-10-15 15:50:14

标签: c# .net ado.net datareader

有人可以告诉我如何修复此错误吗?

 SqlCommand cmd = new SqlCommand(sqlCmd, conn)
 --> conn: Aurgument type 'System.Data.OleDb.OleDbConnection' is not assignable to parameter type 'System.Data.SqlClient.SqlConnection'.

  private void Form1_Load(object sender, EventArgs e)
    {
        string connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=C:\\Users\\KevinDW\\Desktop\\dotNET\\Week 5\\Prak1\\demo1.accdb";

        OleDbConnection conn = new OleDbConnection(connString);

        conn.Open();

        string sqlCmd = "SELECT CursusNaam FROM tblCursus";

        SqlCommand cmd = new SqlCommand(sqlCmd, conn);

        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            listBox1.Items.Add(reader);
        }

        conn.Close();
    }
}

2 个答案:

答案 0 :(得分:0)

你混淆了Sql和OleDb

使用OleDbCommand代替SqlCommand 并使用OleDBDataReader代替SqlDataReader

例如:

  private void Form1_Load(object sender, EventArgs e)
    {
        string connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=C:\\Users\\KevinDW\\Desktop\\dotNET\\Week 5\\Prak1\\demo1.accdb";

        OleDbConnection conn = new OleDbConnection(connString);

        conn.Open();

        string sqlCmd = "SELECT CursusNaam FROM tblCursus";

        OleDbCommand cmd = new OleDbCommand(sqlCmd, conn);

        using (OleDBDataReader reader = cmd.ExecuteReader())
        {
            listBox1.Items.Add(reader);
        }

        conn.Close();
    }
}

答案 1 :(得分:0)

您正在使用SqlCommand / etc,它需要使用SqlConnection对象而不是OleDbConnection。

它是您要连接的SQL数据库吗?如果是,请改用SqlConnection

编辑:显然不是,读取连接字符串......:D