Solved

Adding  the selected item from a combo box to a textfile.

Posted on 2004-08-28
36
224 Views
Last Modified: 2013-12-25
I'd like to know how to add a seledted item in a combo box to a textfile.For example to an .ini file. and a txtfile like notepad.
0
Comment
Question by:zachvaldez
  • 19
  • 15
  • 2
36 Comments
 
LVL 22

Expert Comment

by:DarkoLord
Comment Utility
Hi... use this:

Private Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpString As Any, ByVal lpFileName As String) As Long

Public Sub WriteToINI(ByVal strSection As String, ByVal strkey As String, ByVal strkeyvalue As String, ByVal strfullpath As String)
   'sub to write a key and its value inside an ini section.
   Call WritePrivateProfileString(strSection$, UCase$(strkey$), strkeyvalue$, strfullpath$)
End Sub

Private Sub Command1_Click()
   Dim strTxt As String, ff As String
   ff = FreeFile
   strTxt = Combo1.List(Combo1.ListIndex)

   'write to normal text file
   Open "c:\textfile.txt" For Output As #ff
       Print #ff, strTxt  
   Close #ff  

   'write to ini file
   WriteToINI "section", "key", strTxt, "c:\inifile.ini"
End Sub


Darko
0
 

Author Comment

by:zachvaldez
Comment Utility
Thanks,

How about loading it to the combobox from the textfile?
0
 

Author Comment

by:zachvaldez
Comment Utility
Ho,
oops! in addition also to load it from the textfile using the .ini aproach!

Thanks!
0
 
LVL 22

Accepted Solution

by:
DarkoLord earned 400 total points
Comment Utility
*Sigh*
Here:

Option Explicit
Private Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long

Public Function ReadFromINI(ByVal strSection As String, ByVal strkey As String, ByVal strfullpath As String, Optional ByVal strDefault As String = "") As String
   'function to return the key value of any keys inside an ini section.
   Dim strBuffer As String
   Let strBuffer$ = String$(750, Chr$(0&))
   Let ReadFromINI$ = Left$(strBuffer$, GetPrivateProfileString(strSection$, ByVal LCase$(strkey$), strDefault, strBuffer, Len(strBuffer), strfullpath$))
End Function

Private Sub Command1_Click()
    Dim strStr As String, ff As Long
    ff = FreeFile
    Open "c:\file.txt" For Input As #ff
        strStr = Input(LOF(1), #1)
    Close #ff
   
    Combo1.AddItem strStr
       
    strStr = ReadFromINI("section", "key", "c:\inifile.ini")
    Combo1.AddItem strStr
End Sub

Darko
0
 

Author Comment

by:zachvaldez
Comment Utility
Thanks for sharing your knowledge.

I tried the eg. and it is inputting only 1 item from the combo box and that is good as in the

code: WriteToINI "section", "key", strTxt, "c:\inifile.ini"

The value here is the strTxt that I passed so that now the ini file looked like:
"C:\inifile.ini" - Path
[BooksRead] - Section
BooKid - Key
TDG23G1 -Value

Is it possible to append  Value(strStr) in succession and keep on adding to it as I select it from the combo box and it is save so that I will
have the following:

BookId -TDG23G1
BookId - KKDFHLF4
BookId - L089HHI
 and so forth....

Right now it saves one value and when I select another item form the combo box, it just replaced it and not
Add to the list in the inifile. I guess to make the question clear - How can I add/append value(bookids)
without replacing the bookids already in the ini file....? it should save the bookids there and append bookids depending on the combobox selection.
0
 
LVL 76

Expert Comment

by:GrahamSkan
Comment Utility
That's the way .ini files work. They are for storing key values categorised by sections. If you want to store more key values you should give them different names. You could name them sequentially. It's also best to keep a count, so you know how many to retrieve.

[BooksRead]
Count=3
BookId_1=TDG23G1
BookId_2=KKDFHLF4
BookId_3=L089HHI
0
 
LVL 22

Expert Comment

by:DarkoLord
Comment Utility
Well you can retrieve all subkeys at once... here is the function that adds them to a listbox:

Private Declare Function GetPrivateProfileSection Lib "kernel32" Alias "GetPrivateProfileSectionA" (ByVal lpAppName As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long

Public Sub LoadIniSectionKeysLB(ByVal strSection As String, ByVal lstB As ListBox, ByVal strfullpath As String)
   'sub to load all keys from an ini section into a listbox.
   Dim KeyAndVal() As String, Key_Val() As String, strBuffer As String
   Dim intx As Integer
   Let strBuffer$ = String$(750, Chr$(0&))
     Call GetPrivateProfileSection(strSection, strBuffer, Len(strBuffer), strfullpath)
       KeyAndVal = Split(strBuffer, vbNullChar)
         For intx = LBound(KeyAndVal) To UBound(KeyAndVal)
           If KeyAndVal(intx) = vbNullString Then Exit For
             Key_Val = Split(KeyAndVal(intx), "=")
               If UBound(Key_Val) = -1 Then Exit For
             lstB.AddItem Key_Val(0) '<--to get the keys prior to "=" delimiter only
          'lstB.additem inikey(1) '<--to get the key values past the "=" delimiter only
         Next
       'If lstB.ListCount > 0 Then lst.Selected(0) = True '<<--if you want first list item in listbox selected
     Erase KeyAndVal: Erase Key_Val
End Sub

Darko
0
 

Author Comment

by:zachvaldez
Comment Utility
The idea of differentiating the 'KEY" for new bookids written to the inifile is enterprising.
How is that done in code? There must be somekind of integer variable named to count each combobox selected item.
0
 
LVL 22

Expert Comment

by:DarkoLord
Comment Utility
To count selected item? I don't understand what you mean by that....

Darko
0
 

Author Comment

by:zachvaldez
Comment Utility
As I select an item in th combobox
it would add a counter in the "KEY' say  BookID1 = TGSDLL,Bookid 2 = ILOOOS
in the ini file under "KEY"
and then the abiltity to save the last entry...and keep on adding th bookids. It should check the last entry and integer in the KEY and add 1 to it.

0
 
LVL 22

Expert Comment

by:DarkoLord
Comment Utility
In ini file there is no "last" entry so you would have to create a key to store the last ID value that was written...

Darko
0
 

Author Comment

by:zachvaldez
Comment Utility
Thanks, that was exactly what I am trying to get at.How to create a uniquie key for every item selected in teh combo box. Thanks for your help.
0
 

Author Comment

by:zachvaldez
Comment Utility
GrahamSkin,
 Hi,
Can you please show me an example in code how  to keep track on the number of items
as in the 'KEY" Count=3 you mentioned aboved?

Thanks!
0
 
LVL 22

Assisted Solution

by:DarkoLord
DarkoLord earned 400 total points
Comment Utility
dim key as long, newkey as long, bookID as string
key = CLng(ReadFromINI("BooksRead", "Count", "c:\file.txt")) 'last one written
newKey = key + 1
bookID = "BookID" & CStr$(newKey)
WriteToINI "BooksRead", "Count", Cstr$(newKey), "c:\file.txt"
WriteToINI "BooksRead", bookID, Combo1.List(Combo1.ListIndex), "c:\file.txt"

Darko
0
 

Author Comment

by:zachvaldez
Comment Utility
Thanks DarkoLord for getting back on this quickly. I did know that you can manipulate the reserved word "key".
The reason why I am asking that is I would like to know the frequency each item was selected and based on that I can count it. But this is superved!
0
 
LVL 76

Assisted Solution

by:GrahamSkan
GrahamSkan earned 100 total points
Comment Utility
Sorry for the delay - had to be off-line for a while. I think DarkoLord has it covered, but here is the code that I would use anyway.
In a module:
Option Explicit

Public Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long
Public Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpString As Any, ByVal lpFileName As String) As Long

Function GetProfile(ByVal strSection As String, ByVal strKey As String, strIniFile As String, Optional Default As String) As String
    Dim ReturnedStringLength As Integer
    Dim strDefault As String
    Dim strBuffer As String
    Dim iSize As Integer
   
    If IsMissing(Default) Then
        strDefault = Space$(250)
    Else
        strDefault = Default
    End If
    strBuffer = Space$(250)
    iSize = Len(strBuffer)
   
    ReturnedStringLength = GetPrivateProfileString(strSection, strKey, strDefault$, strBuffer$, iSize, strIniFile)
   
    GetProfile = Left$(strBuffer$, ReturnedStringLength%)

End Function

Public Sub PutProfile(ByVal InAppName As String, ByVal InKeyName As String, ByVal InString As String, ByVal InFileName As String)
    Dim x As Long
    x = WritePrivateProfileString(InAppName, InKeyName, InString, InFileName)
End Sub


In a Form:

Option Explicit

Private Sub Command1_Click()

Dim strFileSpec As String
Dim i As Integer
Dim iBookCount As Integer

strFileSpec = "C:\test1\BooksRead.ini"

For i = 0 To Combo1.ListCount - 1
    iBookCount = Val(GetProfile("Books Read", "Count", strFileSpec))
    iBookCount = iBookCount + 1
    PutProfile "Books Read", "Count", iBookCount, strFileSpec
    PutProfile "Books Read", "BookID_" & iBookCount, Combo1.List(i), strFileSpec
Next i

End Sub

Private Sub Form_Load()
    Combo1.AddItem "TDG23G1"
    Combo1.AddItem "KKDFHLF4"
    Combo1.AddItem "L089HHI"
    Command1.Caption = "Save Combo List"
End Sub
0
 

Author Comment

by:zachvaldez
Comment Utility
Thanks Graham,what if I load the items programmatically from the ini file..
0
 
LVL 22

Expert Comment

by:DarkoLord
Comment Utility
This loads all keys from a section to combobox:


Private Declare Function GetPrivateProfileSection Lib "kernel32" Alias "GetPrivateProfileSectionA" (ByVal lpAppName As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long

Private Sub LoadIniSectionKeys(ByVal strSection As String, ByVal cmB As ComboBox, ByVal strfullpath As String)
   Dim KeyAndVal() As String, Key_Val() As String, strBuffer As String
   Dim intx As Integer
   Let strBuffer$ = String$(750, Chr$(0&))
     Call GetPrivateProfileSection(strSection, strBuffer, Len(strBuffer), strfullpath)
       KeyAndVal = Split(strBuffer, vbNullChar)
         For intx = LBound(KeyAndVal) To UBound(KeyAndVal)
           If KeyAndVal(intx) = vbNullString Then Exit For
             Key_Val = Split(KeyAndVal(intx), "=")
               If UBound(Key_Val) = -1 Then Exit For
             'cmB.AddItem Key_Val(0) '<--to get the keys prior to "=" delimiter only
          cmB.additem inikey(1) '<--to get the key values past the "=" delimiter only
         Next
     Erase KeyAndVal: Erase Key_Val
End Sub

Private Sub LoadFromINI()
   LoadIniSectionKeys "Books Read", Combo1, "C:\file.txt"
End Sub

Darko
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:zachvaldez
Comment Utility
Thanks Darko- for stopping by.
I created a new section ,keycalled
[proposal_count]
Count=5

How will I load these default values?

z
0
 
LVL 22

Expert Comment

by:DarkoLord
Comment Utility
Is this what you want?

Private Sub LoadKeys()
   Dim i As Long
   For i = 1 to Val(ReadFromINI("proposal_count", "Count", "c:\file.ini"))
        Combo1.AddItem ReadFromINI("Books Read", "BookID_" & i, "c:\file.ini")
   Next i
End Sub

Darko
0
 

Author Comment

by:zachvaldez
Comment Utility
Not exactly, but that would work in the other one..
I just want to load and read these 2 lines.

[proposal_count]
Count=5

0
 
LVL 22

Assisted Solution

by:DarkoLord
DarkoLord earned 400 total points
Comment Utility
Dim count As Long
count = Val(ReadFromINI("proposal_count", "Count", "c:\file.ini"))
Msgbox count
0
 

Author Comment

by:zachvaldez
Comment Utility
This is where Iam right now
[MRUProposals]
ActNum0=TDG123
ActNum1=TDG22S
ActNum5=VPL4OS
[Proposal_Count]
Count=3


I like to see these values when I open the ini file..
0
 
LVL 22

Expert Comment

by:DarkoLord
Comment Utility
what are those "0", "1" and "5"? Indexes of combobox items?
0
 

Author Comment

by:zachvaldez
Comment Utility
listindex property

also count is going back to 1 when I close and open the app
0
 

Author Comment

by:zachvaldez
Comment Utility
Darko,

Im getting error here this line:

  cmB.additem inikey(1) '<--to get the key values past the "=" delimiter only

But disregard my last comments.. about thie "also count is going back to 1 when I close and open the app"-My error this part
I could'nt ask for more. Sorry for me asking too many questions. The answer is somwhere there I just have to figure out from all the excellent examples you mentioned.
0
 
LVL 22

Expert Comment

by:DarkoLord
Comment Utility
Sorry that was my error...

cmB.additem Key_Val(1)

should be the correct line...
0
 

Author Comment

by:zachvaldez
Comment Utility
This is what I am trying to load now-TDG123,TDG22S...
[MRUProposals]
ActNum0=TDG123
ActNum1=TDG22S
ActNum2=TDG24S

I created a checkbox that if it is true load these values....from ini file(I have problem here) using the LoadIniSectionKey function

otherwise use the default load from the Database.. whickh loads all bookIDs (I have no problem with this part)--

0
 
LVL 22

Expert Comment

by:DarkoLord
Comment Utility
Private Sub LoadIniSectionKeys(ByVal strSection As String, ByVal cmB As ComboBox, ByVal strfullpath As String)
   Dim KeyAndVal() As String, Key_Val() As String, strBuffer As String
   Dim intx As Integer
   Let strBuffer$ = String$(750, Chr$(0&))
     Call GetPrivateProfileSection(strSection, strBuffer, Len(strBuffer), strfullpath)
       KeyAndVal = Split(strBuffer, vbNullChar)
         For intx = LBound(KeyAndVal) To UBound(KeyAndVal)
           If KeyAndVal(intx) = vbNullString Then Exit For
             Key_Val = Split(KeyAndVal(intx), "=")
               If UBound(Key_Val) = -1 Then Exit For
          cmB.additem Key_Val(1)
         Next
     Erase KeyAndVal: Erase Key_Val
End Sub

Private Sub LoadFromINI()
   LoadIniSectionKeys "MRUProposals", Combo1, "C:\file.ini"
End Sub
0
 

Author Comment

by:zachvaldez
Comment Utility
It is not loading the combo...
0
 

Author Comment

by:zachvaldez
Comment Utility

 For intx = LBound(KeyAndVal) To UBound(KeyAndVal)
           If KeyAndVal(intx) = vbNullString Then Exit For      ---------- when it hits this line
             Key_Val = Split(KeyAndVal(intx), "=")
               If UBound(Key_Val) = -1 Then Exit For
          cmB.additem Key_Val(1)
         Next
     Erase KeyAndVal: Erase Key_Val
End Sub
0
 
LVL 22

Expert Comment

by:DarkoLord
Comment Utility
Do you have this in your ini file?

[MRUProposals]
ActNum0=TDG123
ActNum1=TDG22S
ActNum2=TDG24S
0
 

Author Comment

by:zachvaldez
Comment Utility
YES
0
 
LVL 22

Assisted Solution

by:DarkoLord
DarkoLord earned 400 total points
Comment Utility
I created an ini file "file.ini" on c:\... Then I created a new VB project and put a combobox on it... then I pasted this code and it worked:

Option Explicit
Private Declare Function GetPrivateProfileSection Lib "kernel32" Alias "GetPrivateProfileSectionA" (ByVal lpAppName As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long

Private Sub Form_Load()
    LoadFromINI
End Sub

Private Sub LoadIniSectionKeys(ByVal strSection As String, ByVal cmB As ComboBox, ByVal strfullpath As String)
   Dim KeyAndVal() As String, Key_Val() As String, strBuffer As String
   Dim intx As Integer
   Let strBuffer$ = String$(750, Chr$(0&))
     Call GetPrivateProfileSection(strSection, strBuffer, Len(strBuffer), strfullpath)
       KeyAndVal = Split(strBuffer, vbNullChar)
         For intx = LBound(KeyAndVal) To UBound(KeyAndVal)
           If KeyAndVal(intx) = vbNullString Then Exit For
             Key_Val = Split(KeyAndVal(intx), "=")
               If UBound(Key_Val) = -1 Then Exit For
          cmB.AddItem Key_Val(1)
         Next
     Erase KeyAndVal: Erase Key_Val
End Sub

Private Sub LoadFromINI()
   LoadIniSectionKeys "MRUProposals", Combo1, "C:\file.ini"
End Sub

So there has to be something wrong with your .ini file...
Darko
0
 

Author Comment

by:zachvaldez
Comment Utility
It is now working! Thanks for the time you spent helping me understand inifiles.. I surely understand now how inifiles work.
For that an EXTRA BONUS POINTS!!
0
 
LVL 22

Expert Comment

by:DarkoLord
Comment Utility
You're welcome! Thanks for the points!

Darko
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Introduction I needed to skip over some file processing within a For...Next loop in some old production code and wished that VB (classic) had a statement that would drop down to the end of the current iteration, bypassing the statements that were c…
Most everyone who has done any programming in VB6 knows that you can do something in code like Debug.Print MyVar and that when the program runs from the IDE, the value of MyVar will be displayed in the Immediate Window. Less well known is Debug.Asse…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now