Hi Group!

I need to write the data from multiple TextBoxes (which I've moved to individual string names) into one text file (miscflds.txt). These individual strings will need to be written one on top of the other. To be clear, it will need to look like this:

Item A
Item B
Item C
Item D
etc., so forth and so on.

Conversely, I will need to read the .txt file line by line and move each line to individual string names and then to their specific TextBoxes.

I've looked around on the net and I've not found good examples that I completely understand. Please know I'm working with Visual Basic (Visual Studio 2010 Express).

Could some of you suggest the codes required? I do understand that when writing I will be required to rewrite the entire file as I cannot overwrite a single line within the file.

Thanks again for the help.

Don

You might want to consider using one multi-line textbox. One item on each line. Your code would then be greatly simplified

Imports Syatem.IO

'to fill the textbox
TextBox1.Lines = File.ReadAllLines("C:\Test2.txt")

'to save the data in the textbox, if you use the same filename it will get overwritten.
File.WriteAllLines("C:\Test2.txt", TextBox1.Lines)

If you have to use multiple textboxes something like this might work

Imports System.IO
Imports System.Linq
Public Class Form1
    Dim TextBoxes As List(Of TextBox) = New List(Of TextBox)
    Dim Lines As List(Of String) = New List(Of String)
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        TextBoxes = Me.Controls.OfType(Of TextBox).ToList
        TextBoxes = TextBoxes.OrderBy(Function(x) x.Name).ToList
        FillTextBoxes()
    End Sub
    Private Sub FillTextBoxes()
        Dim Size As Integer = 0
        Lines = File.ReadAllLines("C:\Test2.txt").ToList
        If TextBoxes.Count >= Lines.Count Then
            Size = Lines.Count
        Else
            Size = TextBoxes.Count
        End If
        For i = 0 To Size - 1
            TextBoxes(i).Text = Lines(i)
        Next
    End Sub
    Private Sub SaveData()
        Lines.Clear()
        For Each TB As TextBox In TextBoxes
            Lines.Add(TB.Text)
        Next
        File.WriteAllLines("C:\Test2.txt", Lines)
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        SaveData()
    End Sub
End Class

Edited 3 Years Ago by tinstaafl

tinstaafl,

Unfortunately, I'm not going to be able to move these into one multi-line TextBox.  I'm using this to allow the user to create 36 user-defind inventory fields.  To clarify, these will eventually populate the individual labels of those fields that will store part record data that the end-user will need.  For example, the actual field name in the database is "INV-MISC-COST-1".  The goal is to allow the user to name this field via the label of that field to clarify as to how it is being used.

I know there is a "ReadLine()" command. So I believe I should be able to move each line into an individual string and then to the Label1.Text.  But I first need to move these 36 user-defined names into the .txt file line by line.

Thoughts?

Thanks again,

Don

I threw together a test project. The form has ten textbox controls named TextBox1 through TextBox10. There is one button named btnSave. When the form loads it puts ten strings inito the ten textboxes. Clicking btnSave copies all of the text from the textboxes (in order of name) into a buffer, then writes the buffer to a text file.

Public Class Form1

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles btnSave.Click

        Dim buffer As String = ""

        For i As Integer = 1 To 10
            Dim txt As TextBox = Me.Controls("TextBox" & i)
            buffer &= txt.Text & vbCrLf
        Next

        My.Computer.FileSystem.WriteAllText("d:\temp\save.txt", buffer, False)

    End Sub

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        For i As Integer = 1 To 10
            Dim txt As TextBox = Me.Controls("TextBox" & i)
            txt.Text = "This is line " & i
        Next

    End Sub

End Class

Don,

This type of coding is seductive at first glance, but can be a major PITA to maintain.

Say if at some point you decide that you need to use a RichTextBox (or some other control for that matter) for one of the fields so that you can take advantage of it formating capabilities. You are then forced to rewrite all of the save and load logic to accomodate that one simple change.

Additionally, this technique limits you to having all of the textboxes parented to the same control.

You can achieve the much of the perceived reduced coding effort by simply storing a reference to the control in an array or list of controls and then process that list. Granted you will have to load the list, but you can still use the method that Jim has shown you. However, if you ever need to make any changes, you will only need to modify that loading routine and not all of the others.

You may have noted that I purposely used the word "control" above instead of textbox. There is a good reason for this; it is flexibilty. There is no reason to limit yourself to just textboxes. The TextBox.Text property is inherited from the Control class.

Here is a simple example of the technique. I have only put in very limited error checking.

Public Class Form1

   Private controlTextManager As New ControlTextSaver("savedtb.txt")

   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
      For i = 1 To 3
         controlTextManager.savedControl.Add(Me.Controls("TextBox" & i.ToString))
      Next
      controlTextManager.savedControl.Add(ComboBox1) ' just to make a point that any control's text can be saved this way
      controlTextManager.LoadText()
   End Sub

   Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
      controlTextManager.SaveText()
   End Sub

End Class

Public Class ControlTextSaver
   Private fn As String
   Public Sub New(ByVal savedfilename As String)
      fn = savedfilename
      savedControl = New List(Of Control)
   End Sub

   Private _savedControl As List(Of Control)
   Public Property savedControl() As List(Of Control)
      Get
         Return _savedControl
      End Get
      Set(ByVal value As List(Of Control))
         _savedControl = value
      End Set
   End Property 'savedTextBoxes

   Public Sub SaveText()
      Dim output() As String = (From cntrl In savedControl Select CType(cntrl, Control).Text).Cast(Of String)().ToArray()
      IO.File.WriteAllLines(fn, output)
   End Sub

   Public Sub LoadText()
      If Not IO.File.Exists(fn) Then Exit Sub
      Dim savedtext() As String = IO.File.ReadAllLines(fn)
      If savedtext.Length <> savedControl.Count Then
         Throw New Exception("Saved data problem")
      Else
         For i As Int32 = 0 To UBound(savedtext, 1)
          savedControl(i).Text = savedtext(i)
         Next
      End If
   End Sub
End Class

TnTinMN (and Rev. Jim),

I've not worked with RichTextBox(es) at all and therefore I don't know what they can do. So some of what you've said I know really understand. If you have the time, I would be interested in knowing what the various lines of code do. As I (hopefully) have stated before, I'm very new to Visual Basic (I've taken two courses at the local college in my area). Needless to say it went way to fast and we didn't cover everything indepth. However getting through these struggles have been a great teacher. My appreciation to you and Rev. Jim for helping me.

Thanks again.

Don

Don,

What parts do you not understand?

From my perspective the only thing that I see that may be confusing is the save method. In retrospect, I should not have written it that way for someone who at your level of understanding.

The fancy word for the original method that I employed is LINQ (Language Integrated Query). I tend to through these into examples just to see if people are paying attention and ask questions or if they are cut & paste programmers. I tend not to offer future help to that type of person.

Dim output() As String = (From cntrl In savedControl Select CType(cntrl, Control).Text).Cast(Of String)().ToArray()

does the same thing as:

Dim output(0 To savedControl.Count -1) As String 
For i as Int32 = 0 to savedControl.Count -1
    output(i) = savedControl.Item(i).Text
Next i

It is a somewhat of a programming short cut, but can be a pain to debug if done wrong.

If you are having problems with or just need a refresher on the fundumental stuff, this is a good online tutorial.

http://www.homeandlearn.co.uk/net/vbnet.html

The entire jist of the class "ControlTextSaver" is that it is a generic and re-usable block of code for saving and retrieving the text for a list of controls.

All the controls (button, textbox, label) that you use in a WinForm project are derived from a common ancestor class named "Control", hence the word controls. This follows an inheritance pattern. If you look at the documentation for say the TextBox class's properties, you will wee many of them are listed as being inherited from control. The Text property is one of these inherited properties.

There is a fancy word. polymorphism, used in object oriented programming (yep you doing object oriented programming to a certain extent). Essentially this means that you can change the perceived type of an object like a textbox to look like one of it's ancestors.

Dim c As Control = CType(TextBox1, Control) this is valid because control is an ancestor of TextBox

If fact, the system will allow for an implicit conversion:

Dim c As Control = TextBox1

Therefore, after defining "c" as above, the following two statements will have the same effect as "c" is just a reference to TextBox1.

c.Text = "Fred"
TextBox1.Text = "Fred"

However, "c" will be short on a few of the properties and methods that are specifically defined for the TextBox class. But Textbox will have all of the properties and methods of a Control.

TnTinMN,

I certainly don't want to be a "cut and paste" programmer. I have really enjoyed every aspect of programming. It involves a general pattern of doing thing and lots of logic. The more I learn, the more I know I need to learn. For example, I've used "CType" multiple times. But I don't understand what it means or is trying to imply. I'm sure this is because I'm trying to equate my understanding of the "old" BASIC language with Visual Basic. It's clear there is little similarity.

I'll read the through the link you've suggested. Hopefully there are some examples and practice stuff to do. I learn much more by doing as opposed to just reading about it.

Thanks again. I greatly appreciate all of your help.

Don

... "old" BASIC language with Visual Basic. It's clear there is little similarity.

You have made a very important realization with that one. VB.Net is one of several laguages in the .Net family. Each has it's own pro's and con's. VB tends to be a bit verbose for some, but it is for this reason that I like it. I find it much easier to read than say C#.

The important thing to remember is that while a language may offer certain constructs unique to the that language, you will always have access to the base fucntionality defined in .Net.

Converting an object to a string representation is a good example of this. In .Net every object will have a ToString function defined for it even if it has to work its way up the inheritance tree to find the default ToString defined on the Object Class. Pretty much every Type in .Net derives ultimately from the Object Class.

In VB.Net all of these will produce the string "3"

   Dim s As String
   s = "3"
   s = "3".ToString() ' let's be redundant
   s = 3.ToString()
   Dim i As Int32 = 3
   s = CStr(i) ' a VB function
   s = CType(i, String) ' a VB function
   s = New System.ComponentModel.StringConverter().ConvertToString(i) ' a .Net class
   s = Microsoft.VisualBasic.ChrW(51) ' convert the ASCII value to a character

Here are some links regarding data types and type conversion.

Data Type Summary
http://msdn.microsoft.com/en-us/library/vstudio/47zceaw7%28v=vs.90%29.aspx

Type Conversion Functions
http://msdn.microsoft.com/en-us/library/vstudio/s2dy91zy%28v=vs.90%29.aspx

CType Function
http://msdn.microsoft.com/en-us/library/4x2877xb%28v=vs.90%29.aspx

DirectCast
http://msdn.microsoft.com/en-us/library/7k6y2h6x%28v=vs.90%29.aspx

TryCast
http://msdn.microsoft.com/en-us/library/zyy863x8%28v=vs.90%29.aspx

Constant and Literal Data Types
http://msdn.microsoft.com/en-us/library/dzy06xhf.aspx

Just rember that your search engine is your friend and he likes finding things for you to read.

But it does help if you ask the right question. To find the relevant documention, I found that this search query works pretty good for WinForms help.

msdn forms -social "what you want to find"

The breakdown of the query:

  • "msdn" will get you to Microsoft's site.
  • "forms" since you are working on a WinForm project".
  • "-social" helps prevents you from getting everyone's help request posting on the MSDN forums.
  • "what you want to find" - self explanatory
This question has already been answered. Start a new discussion instead.