我不确定,但我无法获取要在文本框中显示的数据。以下是我到目前为止编写的代码。任何帮助都是最好的。框中没有任何内容,但在测试过程中我收到了消息框。我是不是做错了什么?如果需要,我可以提供访问文件。但它只有五个字段,其中包含数据。
DataSet DataSet1; //use to put data in form
System.Data.OleDb.OleDbDataAdapter dataadapter;
private void Breed_Load(object sender, EventArgs e)
{
    dbconnect = new System.Data.OleDb.OleDbConnection();//database connection variable
    DataSet1 = new DataSet(); //variable to help get info from DB
    dbconnect.ConnectionString = "PROVIDER= Microsoft.Jet.OLEDB.4.0; Data Source=C:/Pets.mdb"; //location of DB to open
    dbconnect.Open(); //open command for DB
    string sql = "SELECT * From tblPets"; //sql string to select all records from the table pets
    dataadapter = new System.Data.OleDb.OleDbDataAdapter(sql, dbconnect); // pulls the records from sql command
    MessageBox.Show("Database is Open");
    dataadapter.Fill(DataSet1, "Pets"); // used the database to fill in the form.
    NavRecords(); //calls NavRecords Method
    dbconnect.Close();
   MessageBox.Show("Database is Closed");
    dbconnect.Dispose(); 
}
private void NavRecords()
{
    DataRow DBrow = DataSet1.Tables["Pets"].Rows[0];
    //PetNametextBox.Text = DBrow.ItemArray.GetValue(1).ToString(); //puts data in textbox
    TypeofPettextBox.Text = DBrow.ItemArray.GetValue(1).ToString();//puts data in textbox
    PetWeighttextBox.Text = DBrow.ItemArray.GetValue(2).ToString();//puts data in textbox
    ShotsUpdatedtextBox.Text = DBrow.ItemArray.GetValue(3).ToString();//puts data in textbox
    AdoptabletextBox.Text = DBrow.ItemArray.GetValue(4).ToString();//puts data in textbox
    BreedtextBox.Text = DBrow.ItemArray.GetValue(5).ToString();//puts data in textbox
}发布于 2011-06-30 03:45:14
从Access数据库中获取数据相当简单。下面是一个示例:
public static DataTable GetBySQLStatement(string SQLText)
{
    System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
    string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Pets.MDB";
    System.Data.OleDb.OleDbConnection Conn = new System.Data.OleDb.OleDbConnection();
    Conn.ConnectionString = ConnectionString;
    cmd.CommandType = CommandType.Text;
    cmd.Connection = Conn;
    cmd.CommandText = SQLText;
    DataSet ds;
    System.Data.OleDb.OleDbDataAdapter da;
    DataTable Table = null;
    Conn.Open();
    da = new System.Data.OleDb.OleDbDataAdapter();
    da.SelectCommand = cmd;
    ds = new DataSet();
    da.Fill(ds);
    if (ds.Tables.Count > 0)
        Table = ds.Tables[0];
    Conn.Close();
    return Table;
}您可以这样调用此函数:
DataTable dt = GetBySQLStatement("SELECT * FROM tblPets");
if (dt != null) {
    // If all goes well, execution should get to this line and
    // You can pull your data from dt, like dt[0][0]
}唯一需要注意的是,这段代码必须编译为32位的应用程序,因为没有64位的Jet驱动程序。默认情况下,Visual Studio将编译为32位和64位混合程序。更改项目设置中的选项以确保其仅为32位。
https://stackoverflow.com/questions/6525930
复制相似问题