inserting data from a text file to textboxes and setting combobox indecies - vb.net

so I am writing a program and trying to setup the save/open features of the program. I have the Save feature working just fine, but can't get the open feature to work.
The issue I'm running into is pulling the data from the text file to the form to fill in the multiple fields and controls. my example code is below
Imports System.IO
Main 1
Sub openFile_Click(sender, e) handles openFile.Click
Dim lineIndex As Integer = 12 'this is my total lines in my file
ofdRead.ShowDialog()
If ofdRead.FileName <> "" then
sr = New StreamReader(ofdRead.FileName)
For i As Integer = 0 To lineIndex -1
sr.ReadLine()
Next
txtField1.Text = sr.ReadLine
cboBox1.SelectedIndex = sr.ReadLine
'this continues through all fields til complete
sr.Close()
End If
End Sub
End Class
I keep getting an error for anything that is being returned as not being a string, and it seems as though the data is being read in reverse as well according to my error output.
Any help would be much appreciated (been searching and pouring over forums for 2 days looking for help)

Thanks Tim Schmelter for your insight. I was calling the wrong data type for the cboBox1 variable. Here is my corrected code (without the For-Loop, turns out i didn't need it)
cboBox1.SelectedItem = sr.ReadLine
so everytime I run into something like that I just have to tell it to put it in as a string instead of an integer

Related

vba - write text to sfile path does not work error

With the help of Userforms and textboxes, i can add new personnel to my personnel file, but there is something wrong in my code and the code does not work. I do get an error while carrying it out. The error says "Compile error: Method or data member not found". I dont know what is wrong with my code, my expectations are that i fill in some Textboxes and i want them added to the already existing seq file (Notepad). But it doesnt let me do that and i dont know why.
I would be happy if someone can find the problem and give a solution.
Thanks in advance.
If you need code from other Commandbuttons,Userforms,etc.. Please tell me.. I dont know entirely what to publish now.
I have already tried changing the Userform_Nieuw names, but to no avail.
Private Sub seq_bestand_maak_databank()
Dim diploma As String
Dim pad As String
pad = "C:\Users\fhaka\Downloads\Overzicht_Personeelsleden.txt"
If UserForm_Nieuw.OptionButton1.Value = True Then
diploma = "Secundair"
ElseIf UserForm_Nieuw.OptionButton2.Value = True Then
diploma = "Bachelor"
ElseIf UserForm_Nieuw.OptionButton3.Value = True Then
diploma = "Master"
End If
If CInt(nieuw.Label1.Caption) = 1 Then
Open pad For Output As #1
Else
Open pad For Append As #1
End If
Write #1, CInt(UserForm_Nieuw.Label1.Caption), UserForm_Nieuw.Voornaam, UserForm_Nieuw.Naam, CInt(UserForm_Nieuw.Aantal_kinderen), UserForm_Nieuw.Geboortedatum, UserForm_Nieuw.Startdatum, "---N/A---", diploma, "0", "---N/A---", "---N/A---", "EOR"
Close #1
End Sub
The goal is that the commandbutton works again and that i can add more personnel now.
The #1 part in Open pad For Output As #1 etc is a file handle. To obtain a file handle, you need to call FreeFile. You cannot just assume that file handle #1 is available at all times.
Try this:
Dim iOutputFile As Integer
iOutputFile = FreeFile
If CInt(nieuw.Label1.Caption) = 1 Then
Open pad For Output As #iOutputFile
Else
Open pad For Append As #iOutputFile
End If
Write #iOutputFile, CInt(UserForm_Nieuw.Label1.Caption), UserForm_Nieuw.Voornaam, UserForm_Nieuw.Naam, CInt(UserForm_Nieuw.Aantal_kinderen), UserForm_Nieuw.Geboortedatum, UserForm_Nieuw.Startdatum, "---N/A---", diploma, "0", "---N/A---", "---N/A---", "EOR"
Close #iOutputFile
It looks like you have not defined the method of the userform. You failed to compile and the highlight is on the UserForm_Nieuw.Voornaam. So I take that is some sort of input field for the first name? Check whether it is really called that or if it does no have the old default name (something like "Textbox275" or some such like your other elements, e.g. OptionButton1 and 2).

Notepad database in VB

I am completely new to VB.net and have only been learning in for a few weeks
I am doing a project where i need to make an EPOS systems using notepad as a data base. I am able to make the values of the buttons appear in the list box, however I have numerous buttons all with different values but only the first value in the text box is appearing each time a different button is pressed.
E.G
When Heineken button pressed "Heineken €5.00" is displayed
when Guiness button pressed "Heineken €5.00" is displayed
Any help is greatly appreciated!
Imports System.IO
Public Class Form1
Private Sub btnHeineken_Click(sender As Object, e As EventArgs) Handles btnHeineken.Click
Dim sr As IO.StreamReader = IO.File.OpenText("DATABASE.txt")
'File DATABASE.TXT is the the debug folder
Dim name As String
Dim stock, price As Double
name = sr.ReadLine
stock = CDbl(sr.ReadLine)
price = CDbl(sr.ReadLine)
lstBox.Items.Add(name & "" & FormatCurrency(price))
name = sr.ReadLine
End Sub
Private Sub BtnGuiness_Click(sender As Object, e As EventArgs) Handles BtnGuiness.Click
Dim sr As IO.StreamReader = IO.File.OpenText("DATABASE.txt")
'File DATABASE.TXT is the the debug folder
Dim name As String
Dim stock, price As Double
name = sr.ReadLine
stock = CDbl(sr.ReadLine)
price = CDbl(sr.ReadLine)
lstBox.Items.Add(name & "" & FormatCurrency(price))
name = sr.ReadLine
End Sub
DATBASE.txt
Heineken
5.00
20
Guiness
4.50
50
Bulmers
5.00
25
Both your methods have exactly the same code. Thus, they do exactly the same thing: They show the contents of the first entry in your text file.
If you want your methods to do different things, you need to put different code in them.
Unfortunately, putting arbitrary code in your methods won't make them do what you want. It looks like you already discovered that. So the next step is to take a more structured approach:
Decide what your button click should do. It looks like you already did that: You want to display "Guiness €4.50" when the "Guiness" button is clicked.
Next, think about how your program can do that. Apparently, that's where you are stuck. You have a text file with a list of entries, how do you get the one you want?
Translate the result of step 2 (the "algorithm") in code.
You tried to do step 3 before step 2. That won't work, and that's the reason why your code doesn't work.
I suggest that you think really hard about step 2 (How do I find data in a text file? How would I do it if I had the file printed out in front of me and were searching for the data personally?), come up with an algorithm and then return here and ask a new question if you need help translating it to code.

Search text file from end of file to beginning of file - VB.NET

I currently have a text file that has fixed fields. There are x number of header lines and x number of detail lines. There is one piece of information I need from the detail line so I can create a record for my program. If there is a way I can loop from the end of the file to the beginning of the file I will be able to accomplish my task.
I have the code below that does the beginning of file to the end...
Using rdr As New StreamReader(_mtLocation)
Do Until rdr.EndOfStream
'// Do code here
Loop
End Using
Is there a way to go from the end of file to the beginning?
If there is any other information you need, please let me know and I will update the question with additional information. Any help is appreciated.
You can read the file into an array of String using the File.ReadAllLines method. Then you would iterate backwards through that array, which would give you each line from bottom to top. For each line, you would iterate backwards through the line.
You can read at different position of the stream by changing the Position property. The problem happens depending on the encoding of the file.
A had a simple file (not unicode) with the number 1 through 9 written into it.
Using s = System.IO.File.OpenRead("test.txt")
For i As Integer = 8 To 0 Step -1
s.Position = i
Console.WriteLine(Chr(s.ReadByte()))
Next
End Using
There's a nice example here but in C#.
stackoverflow.com/a/452945/130611
This is another solution:
Dim TxtLines As New List(Of String)
Using rdr As New StreamReader(_mtLocation)
Do Until rdr.EndOfStream
TxtLines.Add(Reader.ReadLine.ToString())
Loop
End Using
Dim x As Integer
For x = TxtLines.Count To 0 Step -1
'Do your code here...
Next
To get the text of the current line just do this inside the For loop:
TxtLines(x).ToString()

How can I read individual lines of a CSV file into a string array, to then be selectively displayed via combobox input?

I need your help, guys! :|
I've got myself a CSV file with the following contents:
1,The Compact,1.8GHz,1024MB,160GB,440
2,The Medium,2.4GHz,1024MB,180GB,500
3,The Workhorse,2.4GHz,2048MB,220GB,650
It's a list of computer systems, basically, that the user can purchase.
I need to read this file, line-by-line, into an array. Let's call this array csvline().
The first line of the text file would stored in csvline(0). Line two would be stored in csvline(1). And so on. (I've started with zero because that's where VB starts its arrays). A drop-down list would then enable the user to select 1, 2 or 3 (or however many lines/systems are stored in the file). Upon selecting a number - say, 1 - csvline(0) would be displayed inside a textbox (textbox1, let's say). If 2 was selected, csvline(1) would be displayed, and so on.
It's not the formatting I need help with, though; that's the easy part. I just need someone to help teach me how to read a CSV file line-by-line, putting each line into a string array - csvlines(count) - then increment count by one so that the next line is read into another slot.
So far, I've been able to paste the numbers of each system into an combobox:
Using csvfileparser As New Microsoft.VisualBasic.FileIO.TextFieldParser _
("F:\folder\programname\programname\bin\Debug\systems.csv")
Dim csvalue As String()
csvfileparser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
csvfileparser.Delimiters = New String() {","}
While Not csvfileparser.EndOfData
csvalue = csvfileparser.ReadFields()
combobox1.Items.Add(String.Format("{1}{0}", _
Environment.NewLine, _
csvalue(0)))
End While
End Using
But this only selects individual values. I need to figure out how selecting one of these numbers in the combobox can trigger textbox1 to be appended with just that line (I can handle the formatting, using the string.format stuff). If I try to do this using csvalue = csvtranslator.ReadLine , I get the following error message:
"Error 1 Value of type 'String' cannot be converted to '1-dimensional array of String'."
If I then put it as an array, ie: csvalue() = csvtranslator.ReadLine , I then get a different error message:
"Error 1 Number of indices is less than the number of dimensions of the indexed array."
What's the knack, guys? I've spent hours trying to figure this out.
Please go easy on me - and keep any responses ultra-simple for my newbie brain - I'm very new to all this programming malarkey and just starting out! :)
Structure systemstructure
Dim number As Byte
Dim name As String
Dim procspeed As String
Dim ram As String
Dim harddrive As String
Dim price As Integer
End Structure
Private Sub csvmanagement()
Dim systemspecs As New systemstructure
Using csvparser As New FileIO.TextFieldParser _
("F:\folder\programname\programname\bin\Debug\systems.csv")
Dim csvalue As String()
csvparser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
csvparser.Delimiters = New String() {","}
csvalue = csvparser.ReadFields()
systemspecs.number = csvalue(0)
systemspecs.name = csvalue(1)
systemspecs.procspeed = csvalue(2)
systemspecs.ram = csvalue(3)
systemspecs.harddrive = csvalue(4)
systemspecs.optical = csvalue(5)
systemspecs.graphics = csvalue(6)
systemspecs.audio = csvalue(7)
systemspecs.monitor = csvalue(8)
systemspecs.software = csvalue(9)
systemspecs.price = csvalue(10)
While Not csvparser.EndOfData
csvalue = csvparser.ReadFields()
systemlist.Items.Add(systemspecs)
End While
End Using
End Sub
Edit:
Thanks for your help guys, I've managed to solve the problem now.
It was merely a matter calling loops at the right point in time.
I would recommend using FileHelpers to do the reading.
The binding shouldn't be an issue after that.
Here is the Quickstart for Delimited Records:
Dim engine As New FileHelperEngine(GetType( Customer))
// To Read Use:
Dim res As Customer() = DirectCast(engine.ReadFile("FileIn.txt"), Customer())
// To Write Use:
engine.WriteFile("FileOut.txt", res)
When you get the file read, put it into a normal class and just bind to the class or use the list of items you have to do custom stuff with the combobox. Basically, get it out of the file and into a real class asap, then things will be easier.
At least take a look at the library. After using it, we use a lot more simple flat files since it is so easy, and we haven't written a file access routine since (for that kinda stuff).
http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.aspx
I think your main problem is understanding how arrays work (hence the error message).
You can use split and join functions to convert strings into and out of arrays
dim s() as string = split("1,2,3",",") gives and array of strings with 3 elements
dim ss as string = join(s,",") gives you the string back
Firstly, it's actually really good that you are using the TextFieldParser for reading CSV files - most don't but you won't have to worry about extra commas and quoted text etc...
The Readline method only gives you the raw string, hence the "Error 1 Value of type 'String' cannot be converted to '1-dimensional array of String'."
What you may find easier with combo boxes etc is to use an object (e.g. 'systemspecs') rather than strings. Assign the CSV data to the objects and override the "ToString" method of the 'systemspecs' class to display in the combo box how you want with formatting etc. That way when you handle the SelectedIndexChanged event (or similar) you get the "SelectedItem" from the combo box (which can be Nothing so check) and cast it as the 'systemspecs' to use it. The advantage is that you are not restricted to display the exact data in the combo etc.
' in "systemspecs"...
Public Overrides Function ToString() As String
Return Name ' or whatever...
End Function ' ToString
e.g.
dim item as new systemspecs
item.ID = csvalue(1)
item.Name = csvalue(2)
' etc...
combobox1.Items.Add(item)
Let me know if that makes sense!
PK :-)

GetCrossReferenceItems in msword and VBA showing only limited content

I want to make a special list of figures with use of VBA and here I am using the function
myFigures = ActiveDocument.GetCrossReferenceItems(Referencetype:="Figure")
In my word document there are 20 figures, but myFigures only contains the first 10 figures (see my code below.).
I search the internet and found that others had the same problem, but I have not found any solutions.
My word is 2003 version
Please help me ....
Sub List()
Dim i As Long
Dim LowerValFig, UpperValFig As Integer
Dim myTables, myFigures as Variant
If ActiveDocument.Bookmarks.Count >= 1 Then
myFigures = ActiveDocument.GetCrossReferenceItems(Referencetype:="Figure")
' Test size...
LowerValFig = LBound(myFigures) 'Get the lower boundry number.
UpperValFig = UBound(myFigures) 'Get the upper boundry number
' Do something ....
For i = LBound(myFigures) To UBound(myFigures) ‘ should be 1…20, but is onlu 1…10
'Do something ....
Next i
End If
MsgBox ("Done ....")
End Sub*
Definitely something flaky with that. If I run the following code on a document that contains 32 Figure captions, the message boxes both display 32. However, if I uncomment the For Next loop, they only display 12 and the iteration ceases after the 12th item.
Dim i As Long
Dim myFigures As Variant
myFigures = ActiveDocument.GetCrossReferenceItems("Figure")
MsgBox myFigures(UBound(myFigures))
MsgBox UBound(myFigures)
'For i = 1 To UBound(myFigures)
' MsgBox myFigures(i)
'Next i
I had the same problem with my custom cross-refference dialog and solved it by invoking the dialog after each command ActiveDocument.GetCrossReferenceItems(YourCaptionName).
So you type:
varRefItemsFigure1 = ActiveDocument.GetCrossReferenceItems(g_strCaptionLabelFigure1)
For k = 1 To UBound(varRefItemsFigure1)
frmBwtRefDialog.ListBoxFigures.AddItem varRefItemsFigure1(k)
Next
and then:
frmBwtRefDialog.Show vbModeless
Thus the dialog invoked several times instead of one, but it works fast and don't do any trouble. I used this for one year and didn't see any errors.
Enjoy!
Frankly I feel bad about calling this an "answer", but here's what I did in the same situation. It would appear that entering the debugger and stepping through the GetCrossReferenceItems always returns the correct value. Inspired by this I tried various ways of giving control back to Word (DoEvents; running next segment using Application.OnTime) but to no avail. Eventually the only thing I found that worked was to invoke the debugger between assignments, so I have:
availRefs =
ActiveDocument.GetCrossReferenceItems(wdRefTypeNumberedItem):Stop
availTables =
ActiveDocument.GetCrossReferenceItems(wdCaptionTable):Stop
availFigures = ActiveDocument.GetCrossReferenceItems(wdCaptionFigure)
It's not pretty but, as I'm the only person who'll be running this, it kind of works for my purposes.