In this page, you will learn to use ListView control to display records of a table in Microsoft 2007 Access database file. Tthe Microsoft Access database is called institutiondb.accdb in drive D. It has a table called TblInstitution. This table has two fields: ID, and InsName. The ID, and InsName columns are identification number, and name of institutions respectively.
Now you need to create a new Windows Form Application in Visual Studio 2010. Then drag and drop a ListView control on to the form (Form1). The table TblInstitution has two columns. Thus, the ListView to display the table should have two columns as well. To add a column to the ListView, you can use the following form of the Add method:
The Text argument is a string representing the head text of the Column. The Width arguemnt specifies the width of the column. The Alignment argument allows you to specify the alignment of text in that column. There are three alignment constants that can be used: HorizontalAlignment.Left, HorizontalAlignment.Right, and HorizontalAlignment.Center.
The setupListView method below is called from the Form1_Load procedure to add two columns to the ListView (ListView1), view the ListView in details mode, display grid lines, and allow full row selection on an item of the ListView.
In the Form1_Load procedure, you will need to write VB.NET code to call the setListView method, to connect to the Ms. Access, and to add the records from the table to the ListView.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim connection As OleDbConnection
Dim command As OleDbCommand
Dim data_reader As OleDbDataReader
'connect to ms.access database
connection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=d:/institutiondb.accdb")
'reading data from TblInstitution table
command = New OleDbCommand("SELECT * FROM TblInstitution", connection)
data_reader = command.ExecuteReader
'add data to listview
If data_reader.HasRows Then
Dim newitem As New ListViewItem()
newitem.Text = data_reader.GetValue(0) 'first column
newitem.SubItems.Add(data_reader.GetValue(1)) 'second column
You can download the complete code of the program from here.
This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages: