Reading and using text files
Reading and using text files
Reading and using text files
Reading and using text files
Reading and using text files
Reading and using text files Reading and using text files Reading and using text files Reading and using text files Reading and using text files Reading and using text files Reading and using text files Reading and using text files
Reading and using text files Reading and using text files
Reading and using text files
Go Back  Xtreme Visual Basic Talk > > > Reading and using text files


Reply
 
Thread Tools Display Modes
  #1  
Old 08-15-2012, 05:19 AM
Matanic Matanic is offline
Newcomer
 
Join Date: Mar 2012
Location: Florida
Posts: 23
Default Reading and using text files


Greetings all,

I have Form1.vb that users input data into and the Form does some simple math with the data. There are three unique data sets that are needed and entered we will call them 1, 2 and 3.

A friend doing some peer review on this application asked if the form could be made to save the two of the three groups of data for later recall to cut down on data entry.

I figured out how to make some folders in the directory and how to make create and store the .txt files using objwriter.writeline. That works very well.

Code:
Public Class Form3

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If My.Computer.FileSystem.DirectoryExists("C:\QPILABS\Machines\") Then
            'if folder exists do nothing
        Else
            'if folder does not exist create it
            MkDir("C:\QPILABS\Machines\")
        End If

        Dim objwriter As New System.IO.StreamWriter("C:\QPILABS\Machines\" + TextBox5.Text + ".txt")

        objwriter.WriteLine(textbox1.Text)
        objwriter.WriteLine(textbox2.Text)
        objwriter.WriteLine(TextBox3.Text)
        objwriter.WriteLine(TextBox39.Text)
        objwriter.WriteLine(TextBox30.Text)
        objwriter.WriteLine(TextBox4.Text)
        objwriter.WriteLine(TextBox5.Text)
        objwriter.WriteLine(CheckBox3.CheckState)
        objwriter.WriteLine(CheckBox2.CheckState)
        objwriter.WriteLine(CheckBox27.CheckState)
        objwriter.WriteLine(CheckBox28.CheckState)
        objwriter.WriteLine(CheckBox25.CheckState)
        objwriter.WriteLine(CheckBox1.CheckState)

        objwriter.Close()

        Me.Close()
      

    End Sub
Where I am stuck is I use a combo box on the FileToolStripMenu to show the saved .txt files which it does, but I have no idea how to tell VB to select the file and use Readline to read the data and populate the textboxes on the form.

Code:
 Public Sub ToolStripComboBox1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripComboBox1.Click

        For Each s As String In System.IO.Directory.GetFiles("C:\QPILABS\Machines\")
            ToolStripComboBox1.Items.Add(s)
        Next
    

    End Sub
I need a primer here, once the user selects the text file from the combo box how do I get that read into the textboxes on my form?
Attached Images
File Type: jpg Main.JPG (81.4 KB, 8 views)
Reply With Quote
  #2  
Old 08-15-2012, 08:06 AM
DrPunk's Avatar
DrPunkReading and using text files DrPunk is offline
Senior Contributor

* Expert *
 
Join Date: Apr 2003
Location: Never where I want to be
Posts: 1,403
Default

The event you want to use is the SelectedIndexChanged event of the combobox. That event tells you when the user selects a new item in the combobox.

As far as reading files goes you use a StreamReader, assigning it the SelectedItem in the combbox as the file to read.

You can read over the file line by line, and assign the relevant line to the relevant control. That means keeping an index of the line your on and then a case statement on that index as to which control to assign the value to.

Me, personally, I tend to prefer reading a file in one go, the splitting the contents into an array of the lines and using that array.

Code:
' This should really have some error handling but it'll just confuse the issue so I'm not going to put any in.

Dim sr as New Streamreader(ToolStripComboBox1.SelectedItem)
dim file as string
dim lines() as string

' Read the whole file in one hit
file = sr.ReadToEnd
' Finished with the stream so close it
sr.close

' Split the file into its lines
lines = split(file, vbcrlf)
' Finished with the file contents so can clear some memory
file = ""

' Now, based on how you wrote the file, you can assign the file back to the controls
TextBox1.Text = lines(0)
Textbox2.Text = lines(1)
TextBox3.Text = lines(2)
TextBox39.Text = lines(3)
' etc.
__________________
There are no computers in heaven!
Reply With Quote
  #3  
Old 08-15-2012, 12:53 PM
Matanic Matanic is offline
Newcomer
 
Join Date: Mar 2012
Location: Florida
Posts: 23
Default

I get an invalid cast exception was unhandled error when I have this code in:

Code:
Public Sub toolstripcombobox1_selectedindexchanged(ByVal stream As Stream, ByVal e As System.EventArgs) Handles ToolStripComboBox1.SelectedIndexChanged

        Dim sr As New StreamReader("ToolStripComboBox1.Selecteditem")
        Dim file As String
        Dim lines() As String

        file = sr.ReadToEnd
        sr.Close()

        lines = Split(file, vbCrLf)
        file = ""

        textbox1.Text = lines(0)

    End Sub
I also see that that error pops up before the file path is actually highlight and placed in the combo box. I don't know but I am going to guess that it is trying to read the file path before it is actually available

I tried to fire the event off my about buttom but the it was reading a totally wrong file path leading to my desk top VB folder that I thought was kinda strange where it picked that up from.

I find that this code is causing me issues.

Code:
Public Sub IMM1ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IMM1ToolStripMenuItem.Click

        For Each s As String In System.IO.Directory.GetFiles("C:\QPILABS\Machines\")
            ToolStripComboBox1.Items.Add(s)
        Next
Every time I click on the file menu and sub menus I get duplicate entries in the combo box. I am reading on Exit For to see if that could prevent that.

Thank you for the primer Dr
Reply With Quote
  #4  
Old 08-16-2012, 04:35 AM
DrPunk's Avatar
DrPunkReading and using text files DrPunk is offline
Senior Contributor

* Expert *
 
Join Date: Apr 2003
Location: Never where I want to be
Posts: 1,403
Default

Quite a few things wrong there...
Code:
Public Sub toolstripcombobox1_selectedindexchanged(ByVal stream As Stream, ByVal e As System.EventArgs) Handles ToolStripComboBox1.SelectedIndexChanged
This is wrong and will be causing an error. A SelectedIndexChanged event looks like...
Code:
Public Sub ToolStripComboBox1_SelectedIndexChanged(byval sender as object, byval e as System.EventArgs) Handles ToolStripComboBox1.SelectedIndexChanged
In .NET events the first argument is always an object, and is the object that raised the event.

Code:
Dim sr As New StreamReader("ToolStripComboBox1.Selecteditem")
ToolStripComboBox1.SelectedItem should not be in double quotes, otherwise the code will try and open a file called ToolStripComboBox1.SelectedItem and that file won't exist.


Quote:
Every time I click on the file menu and sub menus I get duplicate entries in the combo box.
Clear the contents of the combobox before adding anything to it...
Code:
Public Sub IMM1ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IMM1ToolStripMenuItem.Click

        ToolStripComboBox1.Items.Clear
        For Each s As String In System.IO.Directory.GetFiles("C:\QPILABS\Machines\")
            ToolStripComboBox1.Items.Add(s)
        Next
End Sub
__________________
There are no computers in heaven!
Reply With Quote
  #5  
Old 08-20-2012, 03:05 PM
Matanic Matanic is offline
Newcomer
 
Join Date: Mar 2012
Location: Florida
Posts: 23
Default

I did this

Code:
Public Sub ToolStripComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripComboBox1.SelectedIndexChanged

        Dim sr As New StreamReader(ToolStripComboBox1.SelectedItem)


        Dim file As String
        Dim lines() As String

        ' Reads machine data file to end
        file = sr.ReadToEnd
        ' Closes machine data file
        sr.Close()

        ' File into its lines
        lines = Split(file, vbCrLf)
        ' Clears memory
        file = ""

        ' Popluates form1.vb IMM1 textboxes and checkboxs
        textbox1.Text = lines(0)
        textbox2.Text = lines(1)
        TextBox3.Text = lines(2)
        TextBox39.Text = lines(3)




    End Sub
And I get this:

Code:
Error	1	Overload resolution failed because no accessible 'New' can be called without a narrowing conversion:
    'Public Sub New(path As String)': Argument matching parameter 'path' narrows from 'Object' to 'String'.
    'Public Sub New(stream As System.IO.Stream)': Argument matching parameter 'stream' narrows from 'Object' to 'System.IO.Stream'.	C:\Users\The Fixer\Desktop\VBE Projects\quickchange1.01\quickchange1.01\Form1.vb	25	13	quickchange1.01

I read over the weekend on-line and paged through the books I have but I can't solve this simple little (&$@#!& problem...

Closest I come to an answer would be like saying I am trying to make a Byte have a value over 255 right? I can understand that, a value over 255 would need to be an Integer not a Byte...

So the StreamReader does not want or can't have the value of 'ToolStripComboBox1.SelectedItem'?

I am lost, the books I have talk about StreamReader I did the exercises and those worked but they where a little different, not reading a .txt file etc.

Dumb question time.

On the Error List, below the error, the two Public Sub New, is that VBE suggesting how to fix the error?

Ideas?
Reply With Quote
  #6  
Old 08-21-2012, 05:20 AM
PlausiblyDamp's Avatar
PlausiblyDampReading and using text files PlausiblyDamp is offline
Ultimate Contributor

Forum Leader
* Expert *
 
Join Date: Nov 2003
Location: Newport, Wales
Posts: 2,058
Default

If you look at the documentation for instantiating a streamreader (http://msdn.microsoft.com/en-us/libr...r.streamreader) you can see the various types it will accept.

In your code you are doing
Code:
 Dim sr As New StreamReader(ToolStripComboBox1.SelectedItem)
Which is attempting to pass in a variable of type http://msdn.microsoft.com/en-us/libr...x.selecteditem - this isn't a supported type so you would need to convert it to a more suitable type (probably a string in this case)
__________________
Intellectuals solve problems; geniuses prevent them.
-- Albert Einstein

Posting Guidelines Forum Rules Use the code tags
Reply With Quote
  #7  
Old 08-21-2012, 06:48 AM
DrPunk's Avatar
DrPunkReading and using text files DrPunk is offline
Senior Contributor

* Expert *
 
Join Date: Apr 2003
Location: Never where I want to be
Posts: 1,403
Default

It sounds like you've got Option Strict turned on.

It's good practice to have it turned on, but it means you often have to convert types so that your code will work.

If you look at what a combobox SelectedItem returns you'll see that it returns an Object. That's basically because you can put any class into a combobox if you want. You could fill a combobox with buttons if you really wanted to. It wouldn't show you buttons in the list, it would just show you whatever a button's ToString method returns. But you can put anything into a combobox.

And so, because you can put anything into a combobox, the SelectedItem cannot narrow the returned item any further than Object (everything in .NET has to at least be an object).

But you know what you have put into the combobox. In this case you are putting Strings into the combobox. Therefore it's pretty safe for you to convert the SelectedItem into a string to pass to the StreamReader's constructor.
Code:
Dim sr As New StreamReader(ctype(ToolStripComboBox1.SelectedItem, string))
If you don't have Option Strict turned on then .NET knows that StreamReader wants a string so will attempt to do the conversion itself. If you put strings in then it will work. If you don't put strings in then it will fail, but will only fail at runtime when an attempt to convert something that isn't a string into a string.
__________________
There are no computers in heaven!
Reply With Quote
  #8  
Old 08-23-2012, 08:10 AM
Matanic Matanic is offline
Newcomer
 
Join Date: Mar 2012
Location: Florida
Posts: 23
Default

Dr I did check stricked earlier from some info I found on msdn but it was off. No matter this did the trick thank you!! I can more forward with other things now!!
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump

Advertisement:





Free Publications
The ASP.NET 2.0 Anthology
101 Essential Tips, Tricks & Hacks - Free 156 Page Preview. Learn the most practical features and best approaches for ASP.NET.
subscribe
Programmers Heaven C# School Book -Free 338 Page eBook
The Programmers Heaven C# School book covers the .NET framework and the C# language.
subscribe
Build Your Own ASP.NET 3.5 Web Site Using C# & VB, 3rd Edition - Free 219 Page Preview!
This comprehensive step-by-step guide will help get your database-driven ASP.NET web site up and running in no time..
subscribe
Reading and using text files
Reading and using text files
Reading and using text files Reading and using text files
Reading and using text files
Reading and using text files
Reading and using text files Reading and using text files Reading and using text files Reading and using text files Reading and using text files Reading and using text files Reading and using text files
Reading and using text files
Reading and using text files
 
Reading and using text files
Reading and using text files
 
-->