嗨,我試圖代碼,我想從一個名爲FruitsDatabase.accdb一個Microsoft Access 2016數據庫名爲Fruits_Table表檢索值C#應用程序。然後我想在我的表單中的標籤中顯示這些值,分別稱爲label1,label2,label3。
僅供參考,我在名爲「Fruits.cs」的另一個類文件中使用了名爲Fruit(構造函數,字符串名稱,字符串顏色)的構造函數。然後我將這個構造函數傳入我的PresentationGUI表單。
我的數據庫
數據庫有一個名爲Fruits_Table一個表,該表中有兩列:「名稱」爲水果的名稱和「顏色」的顏色。數據庫中記錄了三項:蘋果 - 紅色,香蕉 - 黃色,梨 - 綠色。
我設法得到工作至今
我設法讓我的數據庫連接成功。所以沒有必要爲此擔心。從數據庫檢索值也很好。
我的問題
我的問題是這樣的:
只有在我的數據庫中的第一個條目似乎顯示,無論我點擊其中的水果圖片框。換句話說,無論我點擊picBox1,picBox2還是picBox3,它都會顯示'Apple'和'Red'
我該如何去遍歷數據庫的行?
using System;
...
using system.Windows.Forms;
using system.Data.OleDb;
namespace project1
{
public partial class PresentationGUI : Form
{
private OleDbConnection aConn;
private OleDbCommand aCmd;
private OleDbDataReader aReader;
private string aConnection;
private string sql;
Fruit[] aFruit = new Fruit[10];
public PresentationGUI()
{
Initialize Component;
//This is working fine.
aConnection = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = FruitsDatabase.accdb;";
sql = "SELECT * FROM Fruits_Table";
aCmd = new OleDbCommand();
aCmd.CommandText = sql;
aCmd.Connection = aConn;
aReader = aCmd.ExecuteReader();
while (aReader.Read())
{
//I have a Fruit constructor that goes: Fruit(string Name, string Color) in another class named Fruit.cs, and I use it here for this form.
aFruit[0] = new Fruit(aReader["Name"].ToString(), aReader["Color"].ToString());
aFruit[1] = new Fruit(aReader["Name"].ToString(), aReader["Color"].ToString());
aFruit[2] = new Fruit(aReader["Name"].ToString(), aReader["Color"].ToString());
}
private void PresentationGUI_Load(object sender, EventArgs e) {...}
//Intended Output: when the user clicks on picBox1 (showing an image of an apple) it should display 'Apple' for label1 and 'red' for label2
//Reality: it displays 'Apple' for label1 and 'Red' for label2
private void picBox1_Click(object sender, EventArgs e)
{
try
{
this.label1.Text = aFruit[0].Name.ToString();
this.label2.Text = aFruit[0].Color.ToString();
}
catch (NullReferenceException) {....}
}
//Intended Output: when the user clicks on picBox2 (showing an image of an Banana) it should display 'Banana' for label1 and 'yellow' for label2
//Reality: it displays 'Apple' for label1 and 'Red' for label2
private void picBox2_Click(object sender, EventArgs e)
{
try
{
this.label1.Text = aFruit[1].Name.ToString();
this.label2.Text = aFruit[1].Color.ToString();
}
catch (NullReferenceException) {....}
}
//Intended Output: when the user clicks on picBox2 (showing an image of an Pear) it should display 'Pear' for label1 and 'green' for label2
//Reality: it displays 'Apple' for label1 and 'Red' for label2
private void picBox3_Click(object sender, EventArgs e)
{
try
{
this.label1.Text = aFruit[2].Name.ToString();
this.label2.Text = aFruit[2].Color.ToString();
}
catch (NullReferenceException) {....}
}
}
}
爲什麼它只顯示我的數據庫的第一行?
不錯!這工作...有點。除了現在我的行似乎是顛倒的:它顯示梨,第一個香蕉是綠色,第二個是黃色,最後是蘋果,紅色時應該是相反的。我應該將計數器設置爲3並將其減1嗎? – 5120bee
如何在您的Select語句中添加訂單,例如sql =「SELECT * FROM Fruits_Table ORDER BY ...」; –