You are on page 1of 5

individual record from the Access database created in the last lesson.

Open Visual Studio


and create a new Windows Application. Name the project AccessConnection. Add three
labels and three textboxes. Change the Text property of the labels to First Name, Last
Name, and Age. Change the Name property of the TextBoxes to txtFirstName,
txtLastName, and txtAge respectively. Add four buttons and change their text to First, Prev,
Next, and Last. Change their Name property to btnFirst, btnPrev, btnNext, and btnLast.
Your form should look like this:

Double click the actual form to generate an event handler for the form's Load event. The
load event will contain the code that queries the values to the database and show the field
values of the first record to their respective text boxes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;

namespace AccessConnection
{
public partial class Form1 : Form
{
private OleDbConnection connection;
private OleDbCommand command;
private OleDbDataAdapter adapter;
private DataSet dataset;
private string firstname;
private string lastname;
private int age;
private int position;

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
connection = new OleDbConnection();
command = new OleDbCommand();
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
adapter = new OleDbDataAdapter();
dataset = new DataSet();

connection.ConnectionString =
@"Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\Members.accdb;" +
"Persist Security Info=False";

command.Connection = connection;
command.CommandText = "SELECT * FROM Members";

adapter.SelectCommand = command;

try
{
adapter.Fill(dataset, "Members");
}
catch (OleDbException)
{
MessageBox.Show("Error occured while connecting to
database.");
Application.Exit();
}

ShowValuesOfRow(0);
}

private void ShowValuesOfRow(int pos)
{
DataRow row = dataset.Tables["Members"].Rows[pos];
position = pos;

firstname = row["FirstName"].ToString();
lastname = row["LastName"].ToString();
age = (int)row["Age"];

txtFirstName.Text = firstname;
txtLastName.Text = lastname;
txtAge.Text = age.ToString();
}
}
}
Example 1
Notice that we use the System.Data.OleDb namespace. This namespace contains the classes
that we will be needing to connect to our Access Database. The namespace System.Data
contains the DataSet class which will holds the data retrieved from the database. We
declared objects for the OleDbConnection (used for connecting to database),
OleDbCommand (handles the sql command), OleDbDataAdapter (used to communicate to
the database and retrive its values), the DataSet, and some fields to hold the values from the
database. The position field will be used to monitor which record to show in the textbox.
Inside the Load event handler of the Form, we initialized the objects neccessary to connect
to the data source. We then set the ConnectionString property of the OleDbConnection
class to the connection string of Access 2007. The connection string parameter Data Source
specifies the path of the Access 2007 file in your system.
We connect the OleDbConnection instance to the OleDbCommand through its Connection
property. We also specified the SQL command through its CommandText property. The
SQL command specifies the we should get all the rows and fields from the Members table.
We set the SelectCommand property of the OleDbDataAdapter instance. We used the
OleDbDataAdapter.Fill() method that executes the command in the SelectCommand
property and put the data into the dataset with the specified table name. Enclosing the Fill()
method in a try..catch handles any exception that might occur.
We called the ShowValuesOfRow() method to show the values of the specified row or
index. We passed 0 as an argument to show the values of the first row. Inside the method,
we retrieve the specified row by accessing the Rows property of the Tables property of the
DataSet object. We passed the name of the table(in this case "Members") as the key to the
Tables property and the value of pos parameter as the index of the Rows property to get a
specific row from the Members table. The result is stored to a DataRow object which
represents a single row in a DataTable. The position is then adjusted. The values of each
columns of the retrieved row is placed to their respective fields and the fields are placed to
their respective text boxes. When you run the program, the form should display the first
record.

Let's add functionality to the four buttons. Lets start with btnFirst. Double click the button
the add an event handler to its Click event.
private void btnFirst_Click(object sender, EventArgs e)
{
ShowValuesOfRow(0);
}
Example 2
The code simply calls the ShowValuesOfRow() method and passes 0 as an argument to
display the first row.
Double click btnLast and add the following code.
private void btnLast_Click(object sender, EventArgs e)
{
int lastIndex = dataset.Tables["Members"].Rows.Count - 1;

ShowValuesOfRow(lastIndex);
}
Example 3
The first line determines the index of the last record from the Members table. We called the
ShowValuesOfRow() method and passed the last index to the method to display the last
row's data.
Double click the btnPrev button and add the following code.
private void btnPrev_Click(object sender, EventArgs e)
{
if (position > 0)
{
position--;
ShowValuesOfRow(position);
}
}
Example 4
We first check if the position is greater than 0. This will prevent the program from querying
a row located at an invalid index such as -1. Inside the if structure, we decrement the
position and called the ShowValuesOfRow() passing the new position as the argument.
Double click the btnNext button and add the following code.
private void btnNext_Click(object sender, EventArgs e)
{
int lastIndex = dataset.Tables["Members"].Rows.Count - 1;

if (position < lastIndex)
{
position++;
ShowValuesOfRow(position);
}
}
Example 5
We retrieve the last index of the rows and check if the position is less than the last index.
This is also to prevent the program on retrieving an invalid index that will cause an
IndexOutOfRange exception to be thrown. The position is incremented by 1 and the values
of the new row is displayed.
Now run the program. Clicking the First button displays the first record. Clicking the Last
button displays the last record. Clicking the prev and next buttons will display the previous
and next records.
We can use the codes in this lesson to connect to an SQL Data Source. All we need to do is
change the type of Provider. You also need to change the connection string to an SQL
Server connection string.

You might also like