C# 从 MS Access 数据库中获取数据并将其显示在列表框中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15128361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting data from MS Access database and display it in a listbox
提问by lexter
How do I read data in ms access database and display it in a listbox. I have the codes here but i got errors.
如何读取 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");
}
}
the errors are here: 1. Error 1 The best overloaded method match for'System.Data.Common.DbDataReader.GetString(int)' has some invalid arguments. 2. Error 2 Argument '1': cannot convert from 'string' to 'int'
错误在这里: 1. 错误 1 'System.Data.Common.DbDataReader.GetString(int)' 的最佳重载方法匹配有一些无效参数。2. 错误 2 参数 '1':无法从 'string' 转换为 'int'
采纳答案by Pyromancer
try this one,
试试这个,
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();
}
then in your search button, insert this,
然后在你的搜索按钮中,插入这个,
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++;
}
It's good to use when you want to show the information of the "FirstName"
in the listBox1_SelectedIndexChanged
if you want. here's an example,
当你想显示的信息这是很好用"FirstName"
的listBox1_SelectedIndexChanged
,如果你想要的。这是一个例子,
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++;
}
}
hope this helps,
希望这可以帮助,
回答by markoo
GetString()
takes an int as the parameter and not a string. Meaning that you must use the index of the column.
GetString()
将 int 作为参数而不是字符串。这意味着您必须使用列的索引。
In your specific circumstance as "FirstName" is the second column the index would be 1:
在您的特定情况下,“名字”是第二列,索引将为 1:
listBox1.Text = Reader.GetString(1);
http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdatareader.getstring.aspx
http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdatareader.getstring.aspx
回答by Gian Acuna
Your error is in this line:
你的错误在这一行:
listBox1.Text = Reader.GetString("FirstName");
You must pass a number in the GetString()
function.
您必须在GetString()
函数中传递一个数字。
回答by saeed
change
改变
listBox1.Text = Reader.GetString("FirstName");
to
到
listBox1.Text = Reader.GetString(0); // zero base ordinal of column
回答by Jens Kloster
Thy using a While loop
你使用 While 循环
while(reader.Read())
{
listbox1.Items.Add(reader["FirstName"]);
}
This moves through all the rows you selected. reader.Read()
returns false
if there are no more rows.
这将遍历您选择的所有行。如果没有更多行,则reader.Read()
返回false
。
Also: if you Want to retrive valmue from a column I suggest you do it with the index ón the reader
instance. Like my example.
另外:如果您想从列中检索 valmue,我建议您使用reader
实例的索引来进行。就像我的例子。
var value = reader["ColumnName"];
This increases readability comparing to
与相比,这增加了可读性
var value = reader.GetString(0);
UPDATE
更新
If you want to only display the fist value - I suggest you use cmd.ExecuteScalar()
and the adapt you sql to only return the value you need:
如果您只想显示第一个值 - 我建议您使用cmd.ExecuteScalar()
并调整您的 sql 以仅返回您需要的值:
using(OleDbCommand cmd = new OleDbCommand("SELECT firstname from TableAcct", conn))
{
conn.Open();
var firstName = cmd.ExecuteScalar();
}
Be aware the this will give you the first"FirstName" in the table. And since there is no "order by firstname"
or "where someKey = 1"
- this might not rturn that you expected.
请注意,这将为您提供表中的第一个“名字”。而且由于没有"order by firstname"
或"where someKey = 1"
- 这可能不会像您预期的那样转变。
回答by Pir Fahim Shah
If you want to create MS Access data base and to access it, and to display data in some component, like here i will show you.how to connect with MS Access Data Base and display data from data base in Label. First of all create any Access data base like here "PirFahimDataBase". Now in your Visual Studio go to the menu and do this
如果您想创建 MS Access 数据库并访问它,并在某个组件中显示数据,就像这里我将向您展示如何连接 MS Access 数据库并在 Label 中显示数据库中的数据。 首先创建任何 Access 数据库,如“PirFahimDataBase”。现在在您的 Visual Studio 中转到菜单并执行此操作
- Click Data
- Add New Data Base
- Click Next
- Click New Connection
- Now change the Data Source by clicking Change and select Microsoft Access data base files
- Click Browse for selecting your created data base
- 点击数据
- 添加新数据库
- 点击下一步
- 单击新建连接
- 现在通过单击更改并选择 Microsoft Access 数据库文件来更改数据源
- 单击浏览以选择您创建的数据库
Now in Button ClickEvent paste these code which will get data from data base and will show it in the label
现在在按钮 ClickEvent 中粘贴这些代码,这些代码将从数据库中获取数据并将其显示在标签中
using System.Windows.Forms; //these two lines should be written before namespace at top of the program
using System.Data.OleDb;
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
@"Data source= C:\Users\pir fahim shah\Documents\PirFahimDataBase.accdb";
try
{
conn.Open();
MessageBox.Show("connected successfuly");
OleDbDataReader reader = null; // This is OleDb Reader
OleDbCommand cmd = new OleDbCommand("select TicketNo from Table1 where Sellprice='6000' ", conn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
label1.Text= reader["TicketNo"].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show("Failed to connect to data source");
}
finally
{
conn.Close();
}
}//end of button click event
回答by sgdhgsagsaf
DataColumn[] PrimaryKeyColumn = new DataColumn[1]; //Define Primary coloumn
DataSet dataSet = new DataSet();
DataTable dataTable = new DataTable();
ReadAndUpdateExcel.ReadExcel(strPath, sheetName, out dataSet);
dataSet.Tables.Add(dataTable);
PrimaryKeyColumn[0] = dataSet.Tables[0].Columns[0];
dataSet.Tables[0].PrimaryKey = PrimaryKeyColumn;
string num = dataSet.Tables[0].Rows[dataSet.Tables[0].Rows.IndexOf(dataSet.Tables[0].Rows.Find(strTCName))]["ACNO"].ToString();
//string country