[英]Get list of IDs from Access Database using OleDbDataReader
將 Microsoft Access 數據庫用於 Web 應用測驗管理器,我有一個帶有 ID 列的表,其中包含一個如下所示的 ID 列表:
ID Answer QuesDescription QuesAnswer QuestionNum
1 1 Example Example 1
3 3 Example Example 2
4 4 Example Example 3
6 1 Example Example 4
使用查詢SELECT ID FROM (QuizName)
和OleDbCommand
我設法從數據庫中獲取 ID 值並存儲到OleDbDataReader reader
中。 但我不知道如何從閱讀器獲取 ID 值並將它們存儲為字符串列表。 有誰知道如何做到這一點?
我試過使用類似的東西
public List<string> GetIDValueFromQuestionNumber(string quizNumber)
{
try
{
string strSQL = string.Concat("SELECT count(ID) as RowCount FROM ", quizNumber);
List<string> resourceNames = new List<string>();
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(strSQL, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
reader.Read();
int rowCount = (int)reader["RowCount"];
strSQL = string.Concat("SELECT ID FROM ", quizNumber);
command = new OleDbCommand(strSQL, connection);
using (reader = command.ExecuteReader())
{
while (reader.Read())
{
resourceNames.Add(" " + reader.GetString(0));
}
}
connection.Close();
for (int count = 0; count < rowCount; count++)
{
int value = (int)reader.GetValue(count);
resourceNames.Add(value.ToString());
}
}
return resourceNames;
}
catch (Exception e)
{
return null;
}
}
但沒有運氣。
我應該注意,這些表格的深度可能會有所不同。
我建議這種方法。
說一個表單 - DataGridView 來顯示我們的數據。
並說一個列表框來顯示您在該列表中建立的 id 列表
所以,這個表格:
和按鈕點擊代碼:
private void button1_Click(object sender, EventArgs e)
{
// load up our data list with Hotels
string strSQL =
@"SELECT ID, FirstName, LastName, City, HotelName
FROM tblHotelsA ORDER BY HotelName";
DataTable rstData = MyRst(strSQL);
dataGridView1.DataSource = rstData;
// now build up a list of id in to string colleciton
List<string> MyIDList = new List<string>();
foreach (DataRow MyOneRow in rstData.Rows)
{
MyIDList.Add(MyOneRow["ID"].ToString());
}
// Lets set the id list to a listbox
listBox1.DataSource = MyIDList;
}
DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (OleDbConnection conn = new OleDbConnection(Properties.Settings.Default.AccessDB))
{
using (OleDbCommand cmdSQL = new OleDbCommand(strSQL, conn))
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
現在我們得到/看到這個:
所以,拉桌子。 顯示它,做任何事情。
然后使用 SAME 表,簡單地循環每一行,獲取 ID 並添加到您的列表中。
當然,人們可能會在上面的列表中隱藏“id”(只需使用編輯列添加列 - 只添加您想要的列)。 您仍然可以從數據源獲取/抓取/使用任何列 - 不需要顯示這些列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.