gpt4 book ai didi

c# - 从 MS Access 数据库中获取数据并将其显示在列表框中

转载 作者:太空狗 更新时间:2023-10-29 22:33:04 27 4
gpt4 key购买 nike

如何读取 MS Access 数据库中的数据并将其显示在列表框中。我这里有代码,但出现错误。

 private void button3_Click(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\Sisc-stronghold\mis!\wilbert.beltran\DataBase\DataStructure.accdb"))
using(OleDbCommand cmd = new OleDbCommand(" SELECT * from TableAcct", conn))
{
conn.Open();
OleDbDataReader Reader = cmd.ExecuteReader();
//if (Reader.HasRows)
if (Reader.HasRows)
{
Reader.Read();
listBox1.Text = Reader.GetString("FirstName");
}
}

错误在这里:1. 错误 1 ​​The best overloaded method match for 'System.Data.Common.DbDataReader.GetString(int)' has some invalid arguments.2. 错误 2 参数 '1': 无法从 'string' 转换为 'int'

最佳答案

试试这个,

       List<String> firstName = new List<String>();
List<String> lastName = new List<String>();

private void loadButton_Click(object sender, EventArgs e)
{
cn.Open();
OleDbDataReader reader = null;
cmd = new OleDbCommand("select* from Records", cn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
firstName.Add(reader["FirstName"].ToString());
lastName.Add(reader["LastName"].ToString());
}
cn.Close();
}

然后在你的搜索按钮中,插入这个,

private void searchButton_Click(object sender, EventArgs e)
{
clearSearchResult();
try
{
int totalItems = FirstName.Count;
int count = 0;
while (count < totalItems)
{
if (textBox6.Text == FirstName[count].ToString())
{
listBox1.Items.Add(FirstName[count].ToString());
count = 100;
}
else
{
count++;
}

如果你想在 listBox1_SelectedIndexChanged 中显示 "FirstName" 的信息,如果你愿意的话,使用它是很好的。这是一个例子,

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int totalItems = lastName.Count;
int count = 0;
while (count < totalItems)
{
if ((listBox1.SelectedItem.ToString()) == firstName[count].ToString()))
{
textBox1.Text = firstName[count].ToString();
textBox2.Text = lastName[count].ToString();
count = 100;
}
else
{
count++;
}
}

希望对你有帮助,

关于c# - 从 MS Access 数据库中获取数据并将其显示在列表框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15128361/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com