The following are the complete code to get data from Access database:
First, we connect to the database.
public DataTable getData()
{
string cnStr = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=HR.mdb";
OleDbConnection cn = new OleDbConnection(cnStr);
string sql = "select * from Employees";
OleDbDataAdapter da = new OleDbDataAdapter(sql, cn);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
Then, we load the data to Listview control
public void loadToListView()
{
DataTable dt = getData();
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow row = dt.Rows[i];
int id = Convert.ToInt32(row["EmpID"]);
string fName = row["FirstName"].ToString();
string lName = row["LastName"].ToString();
Employees emp = new Employees(id, fName, lName);
ListViewItem item = new ListViewItem(id.ToString());
item.SubItems.Add(fName);
item.SubItems.Add(lName);
item.Tag = entity;
lvEmp.Items.Add(item);
}
}
Make sure that you had copied the Access database file into bin/Debug.
Hope this helps!
Saturday, March 31, 2012
How to get data from Access database in C#?
4:37 AM
Unknown
1 comment
1 comments:
yes it helped!!!
Post a Comment