How do I read data in ms access database and display it in a listbox. I have the codes here but i got errors.
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'
Your error is in this line:
You must pass a number in the
GetString()
function.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
Now in Button ClickEvent paste these code which will get data from data base and will show it in the label
GetString()
takes an int as the parameter and not a string. Meaning that you must use the index of the column.In your specific circumstance as "FirstName" is the second column the index would be 1:
http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdatareader.getstring.aspx
change
to
Thy using a While loop
This moves through all the rows you selected.
reader.Read()
returnsfalse
if there are no more rows.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.This increases readability comparing to
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: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.try this one,
then in your search button, insert this,
It's good to use when you want to show the information of the
"FirstName"
in thelistBox1_SelectedIndexChanged
if you want. here's an example,hope this helps,