borderAndreaVB free resources for Visual Basic developersborder

borderAndreaVB Visual Basic and VB.NET source code resources - Copyright © 1999-2007 Andrea Tincaniborder

AndreaVB | Forum | News | Downloads | Register | Help | Member List | Statistics | Search | PM | Profile

Print This Topic
Previous Topic (How to make a copy of an existing Acess Datasbe witn new Name ?)Next Topic (Taking out Limitation of Image Combo) New Topic New Poll Post Reply
AndreaVB Forum : VB General : Using Access with VB6 Solved Topic
Poster Message
iliekater
Level: Master

Registered: 04-02-2005
Posts: 123

icon Using Access with VB6

I am new on Access , so I'd like to ask for your help . Lets say we have a data base file (i.e. MyDataBase ) with 3 fields in it and we also have 3 text boxes on a form . How can we use those 3 text boxes in order to modify the data of the 3 fields in the given data base file ?

09-09-2006 at 12:50 PM
View Profile Send Email to User Show All Posts | Quote Reply
yronium
Level: Moderator


Registered: 14-04-2002
Posts: 907
icon Re: Using Access with VB6

Well it's a wide range question.
First, you don't have the fields in the database, but in one table in the database. The containing levels are Database -> Tables -> Fields -> Data.
Before trying to fill the controls with data, you have anyway to connect to the database, open the table you need, and read the contents of desired fields.

In order to connect to database, you need a data-provider software with an appropriate db engine, and a data/VB6 communication interface. Nowadays, the avaliable data-providers are ODBC and OLE DB, and both are included into the OS. The difference between using one or another is only in the connection string syntax to use. I suggest you to use OLE DB, that has a more recent technology.
The db engine to use to connect to MSAccess dbs is named MS Jet, and the latest version is 4.0. You got in your pc if you have installed VB6, or MSOffice 2000 or later.
The interfaces to use between Jet and VB6 are various: RDO, JRO, DAO, ADO, or others. ADO and DAO are the latest ones, and the more used. ADO is the last, and its last version is 2.8, but it's enough the 2.1 to work good.
I suggest you to use ADO: check for ActiveX Data Objects 2.8 in VB6's Project/References menu. So from now on, I'll speak like you decided to use ADO.

First step is connecting to database. So you need a way to pass to the data provider all the parameters to open the connection, included the db engine to use. All these parameters are specified by one single connection property: the ConnectionString. You build a connection string, open the database, then you are ready to open and read the desired table.

To read a table - or just some fields of it, or just some data matching some criteria - the dbs are using to execute an SQL query. You can build this query in SQL language, and normally the db show directly the result. But now you're working out from the db interface, then you need a way to preserve these result in memory, in order to fill textboxes later. So you need a tool to store temporarily data: this tool is a Recordset object.
Once the connection is open, you build an sql instruction, then execute it and put the results into a recordset. There are several ways to do it.

To associate data to textboxes (or to other types controls) there are three fundamental methods, but all require data are already into a recordset:
    - simply read each field of the recordset, and set the textbox Text property equal to field's value;
    - set each textbox' DataSource property on the recordset;
    - put and ADODC control onto your form, set its Recordset property on the recordset (or directly assign the sql instruction to its RecordSource property. This way you don't need anymore to have a recordset in memory), then set each textbox' DataSource property on the ADODC control.
The second and the third methods automatically change values in the textboxes when moving to another record in the recordset, but the first is more flexible and it's not hard to update the textboxes linked in this way too.
My favourite one is the first method. Don't ask me why: every programmer prefer a way instead of another, maybe I like its flexibility, but anyway I can choose another method time by time, according to my application design requirements.
There are other ways, but all are variants of these three, more or less.

So let's get our hands dirty. Assuming that you have a database named MyDataBase.mdb, having a table named Table1, with the ID, Name, Surname, Address, City fields, the steps are as following (sample of first method):
Option Explicit

Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset

Private Sub Form_Load()
    Dim cnstr As String
    Dim sql As String
    ' open the connection
    Set cn = New ADODB.Connection
    cnstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\ProgramFiles\MyData\MyDataBase.mdb;Mode=ReadWrite;Persist Security Info=False"
    cn.Open cnstr
    ' open the recordset
    Set rs = New ADODB.Recordset
    sql = "SELECT * FROM Table1 ORDER BY Surname;"
    rs.CursorLocation = adUseClient
    rs.Open sql, cn, adOpenDynamic, adLockOptimistic, adCmdText
    ' now fill the textboxes
    FillControls
End Sub

' fill the textboxes with the fields values
' this code is in a separate routine to be called by the moving buttons
Private Sub FillControls()
On Error Resume Next
    Me.txtName.Text = rs.Fields("Name").Value
    Me.txtSurname.Text = rs.Fields("Surname").Value
    Me.txtAddress.Text = rs.Fields("Address").Value
    Me.txtCity.Text = rs.Fields("City").Value
    Me.txtID.Text = rs.Fields("ID").Value
End Sub

' move on next record
Private Sub btnMoveNext_Click()
On Error Resume Next
    ' move on...
    rs.MoveNext
    ' ... and re-fill the textboxes
    FillControls
End Sub

' move on previous record
Private Sub btnMovePrevious_Click()
On Error Resume Next
    ' move on...
    rs.MovePrevious
    ' ... and re-fill the textboxes
    FillControls
End Sub

' move on last record
Private Sub btnMoveLast_Click()
    ' move on...
    rs.MoveLast
    ' ... and re-fill the textboxes
    FillControls
End Sub

' move on first record
Private Sub btnMoveFirst_Click()
    ' move on...
    rs.MoveFirst
    ' ... and re-fill the textboxes
    FillControls
End Sub

Private Sub Form_Unload(Cancel As Integer)
    ' close and destroy the recordset and the connection variables
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
End Sub
The code above requires a form with five textboxes (txtName, txtSurname, txtAddress, txtCity, txtID - notice they have not necessarily to be in the same order of the fields) and four commandbuttons (btnMoveNext, btnMovePrevious, btnMoveLast, btnMoveFirst). The errors can occur if the recordset is empty (no records found in the table), or one field is empty, or when you click MoveNext on the last record or MovePrevious on the first record: usually there are other ways to manage these cases, but now I'm explaining you the very basics. We'll talk about it later, when you know a bit more.

It'd be simple enough to be understood, even if it doesn't allow other simple operations like adding, deleting and filtering records. I leave to you the pleasure to find how to implement these feature.
You should also study the various options of Recordset's object properties (I wrote adCmdText, adOpenDynamic, adLockOptimistic, and so on. You will study what they mean), so I suggest you a good book, as ADO is a powerful tool with a lot of features. And don't forget to read the related threads in forum's Database section, where you can find plenty of code snippets to do the job.

Hope it's enough to startup. Ask for any other question.

PS. time ago, I posted a small sample project. Please feel free to download and study it, you can find it here.

[Edited by yronium on 09-09-2006 at 06:49 PM GMT]

____________________________
Real Programmer can count up to 1024 on his fingers

09-09-2006 at 05:34 PM
View Profile Send Email to User Show All Posts | Quote Reply
iliekater
Level: Master

Registered: 04-02-2005
Posts: 123
icon Re: Using Access with VB6

Thanks alot . It looks like I have alot to study (at least I already know and used some of DAO and ADO stuff - thanks to other people from here that were very kind to help me) . Thanks again .

11-09-2006 at 06:48 PM
View Profile Send Email to User Show All Posts | Quote Reply
iliekater
Level: Master

Registered: 04-02-2005
Posts: 123
icon Re: Using Access with VB6

Thanks alot yronium ! I can finally not only use data base in my VB programs just to show their contents ( with DataGrid controlers etc) , but now I can also actually modify thei contents in real time ! Your reply and your tutorial helped me a lot .

18-09-2006 at 07:39 PM
View Profile Send Email to User Show All Posts | Quote Reply
iliekater
Level: Master

Registered: 04-02-2005
Posts: 123
icon Re: Using Access with VB6

Well , I found out something : I think it's much easier to use a Adodc control instead of writing all that code ! An Adodc control has eitherway a database file and a table (recordset) set (which , moreover , can be set visually , instead of writting code) .

However , I want to ask something else too :
In the code you provided me , there is line like this :
DataBaseCUSTOMERS.Open ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Factory\Pixis\Resourses\Customers.mdb;Mode=ReadWrite;Persist Security Info=False")

well , some time it's not possible to know the path of the database file (i.e. the user may choose among more than one different files in different paths) . In this case I'll have to provide manually the path , probably via a string variable , to the Data Source . But the problem is how can I do that , since the Data Source text is already among the "" symbols ?

18-09-2006 at 09:16 PM
View Profile Send Email to User Show All Posts | Quote Reply
yronium
Level: Moderator


Registered: 14-04-2002
Posts: 907
icon Re: Using Access with VB6

Well, this is in fact the advantage of a connectionstring: that it can me modified at runtime.
I'll show you a sample:
Private Sub btnConnectDb_Click()
    Dim dbpath As String
    Dim cnstring As String
    ' in this sample we get db path by an InputBox call,
    ' but we can obtain the path in many other ways
    dbpath = InputBox("Please insert the path of the database to be opened")
    ' build the connection string....
    cnstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=""
    cnstring = cnstring & dbpath
    cnstring = cnstring & ";Mode=ReadWrite;Persist Security Info=False"
    ' ....then pass it to the Open method
    DataBaseCUSTOMERS.Open cnstring
End Sub

You can build the connection string before opening, using some variables for all the parameters you need to specify at runtime. You can either read db path in a file, or get it by an inputbox, or open a CommonDialog window to select the file, or whatever.

Hope it helps.

PS: I prefer not to use the Adodc control, as I like building my custom controls to surf the database, but as I said already, everyone has its programming preferences. I explained you how a recordset works, in order you to understand the recordset that lies under the Adodc control. Once you are able to manage that recordset, you can manage the Adodc control as well, or a simple recordset object instead, according to your project's goals. I often do use it even if it is not my favourite.

____________________________
Real Programmer can count up to 1024 on his fingers

22-09-2006 at 09:30 AM
View Profile Send Email to User Show All Posts | Quote Reply
nkmomin
Level: Protégé

Registered: 21-09-2006
Posts: 6
icon Re: Using Access with VB6

Hi buddy you can also use in this way using '& ' operator.

the sample is

    ' build the connection string....
    cnstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbpath & ";Mode=ReadWrite;Persist Security Info=False"



the whole statement in one line.

thanks

22-09-2006 at 11:42 AM
View Profile Send Email to User Show All Posts | Quote Reply
iliekater
Level: Master

Registered: 04-02-2005
Posts: 123
icon Re: Using Access with VB6

I know , I know ...  
I just don't know how I asked just a silly question . . .    
It was obvius that I could simply use the & operator . I'm sorry for bothering you .

24-09-2006 at 04:15 PM
View Profile Send Email to User Show All Posts | Quote Reply
AndreaVB Forum : VB General : Using Access with VB6 Solved Topic
Previous Topic (How to make a copy of an existing Acess Datasbe witn new Name ?)Next Topic (Taking out Limitation of Image Combo) New Topic New Poll Post Reply
Surf To:


Not Logged In? Username: Password: Lost your password?
Partners: Download Actual Software | Free Software Download
borderAndreaVB free resources for Visual Basic developersborder

borderAndreaVB Visual Basic and VB.NET source code resources - Copyright © 1999-2007 Andrea Tincaniborder