Uncle Wiggy Uncle Wiggy - 6 months ago 7
Vb.net Question

onLoad set 10 ( or more) button.text from a txt file

I have a simple form with 10 or more buttons.
These are named Button1, Button2 etc.
I want the user to save a simple txt file for each button text in a folder. Why? Well Each end user will want to have different names for each button from the next user who will use the form. Each user will need to set his own text description to suit his needs. (once at set up) So in a folder location I have... Button1.txt, Button2.txt etc each with a default starting text.
On loading the form, I want to loop through the txt files and add the user edited names to each of the buttons.

I can get this to work long hand...doing it one at a time,
but I know I should be able to loop through simply...

I have tried several variations on this

For i = 1 To 10
Dim FILE_NAME As String = "C:\QuickButtons\ButtonTxt\Button" & i & ".txt"
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Me.Controls("Button" & i).Text = objReader.ReadToEnd

I keep getting "Object reference not set to an instance of an object."

For someone out there this is an easy one... if I had hair, I would be pulling it out!
So I send you many thanks in advance.


The problem is most likely here:

Me.Controls("Button" & i).Text = objReader.ReadToEnd

This will only succeed if the buttons are contained directly by the Form. If they are in a different container, like a Panel, then it would fail.

One solution is to search for the control like this:

    For i As Integer = 1 To 10
        Dim FILE_NAME As String = "C:\QuickButtons\ButtonTxt\Button" & i & ".txt"
        If System.IO.File.Exists(FILE_NAME) Then
            Dim matches() As Control = Me.Controls.Find("Button" & i, True)
            If matches.Length > 0 AndAlso TypeOf matches(0) Is Button Then
                Dim btn As Button = DirectCast(matches(0), Button)
                btn.Text = System.IO.File.ReadAllText(FILE_NAME)
            End If
        End If