Retriving Data from database and creating object of it?

qadeer37

Well-known member
Joined
May 1, 2010
Messages
63
Location
Hyderabad,pakistan
Programming Experience
1-3
Public Class Form1
Public Sub MakeConnection()
Dim sConnection As String
Dim dbConn As db.OleDb.OleDbConnection



sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\QADEER\Documents\Customer.accdb;Persist Security Info=False;"

dbConn = New db.OleDb.OleDbConnection(sConnection)
dbConn.Open()


' MessageBox.Show(dbConn.State.ToString())



Dim sql, fn, ln As String
Dim dbCmd As db.OleDb.OleDbCommand
Dim dbReader As OleDb.OleDbDataReader

sql = "Select * From Customer; "


dbCmd = New db.OleDb.OleDbCommand(sql, dbConn)
dbReader = dbCmd.ExecuteReader()
Do While dbReader.Read()

fn = System.Convert.ToString(dbReader("FirstName"))
ln = System.Convert.ToString(dbReader("LastName"))
lstCustomers.Items.Add(ln + " " + fn)

Loop

End Sub

This gets FirstName and LastName from database and creates a string of it and adds it to list.
Is it possible to make an object with FirstName and LastName as property.
so that it could be accessed like c=lstCustomers.SelectedItem as Customer
c.FirstName
c.LastName
:rolleyes:
 
You would have to define a Customer class with those properties yourself. You can then create instances of that class using the data from your data reader.

Also, you don't need to call Convert.ToString. The values are strings already, so you can either cast as type String or use the GetString method of the DataReader.
 
Read the DW2 link in my sig, following the Creating a Simple Data App tutorial

At the end of it you'll have a DataSet, which is a collection of DataTable. One of these DataTable will be called Customer, and it will have columns called FirstName and LastName..
DataTable is a collection of CustomerRow objects, and each of these will have properties called FirstName and LastName


Thus, the datarow is the object that represents your Customer
 
Back
Top