updating textbox.text in a tabpage - vb.net-2010

I've got an app with numerous textboxes that's basically a form to fill out. There are several tabpages in a tab control. In saving the data, I simply loop through the textboxes, get their names and text and put that in a text file with a '|' as a seperator. That works great and I can see all my textboxes and the data in the text file. Now comes the problem. When I read the file back (to load saved data back into the form) it loops through the control name and changes the text to whatever was in the file. It works fine with the textboxes that are on the form, but fails when it gets to the first textbox that is on a tabpage. How can I fix that? And if there's a better way to save the data, I'm all ears.
Here's the code that writes the file:
Private Sub savefile(file As String)
Dim ctl As Control = Me
Dim sw As System.IO.StreamWriter
sw = My.Computer.FileSystem.OpenTextFileWriter(file, False)
Do
ctl = Me.GetNextControl(ctl, True)
If ctl IsNot Nothing Then
If TypeOf ctl Is TextBox Then
sw.WriteLine(ctl.Name.ToString.Substring(3) & "|" & ctl.Text)
End If
End If
Loop Until ctl Is Nothing
sw.Close()
End Sub
Here's the code that reads the file and updates the textboxes:
Private Sub ReadFile(filename)
Dim strfilename As String = filename
Dim num_rows, x, y As Integer
Dim strarray(1, 1) As String
Dim ctrl As Control = Me
'Check if file exist
If File.Exists(strfilename) Then
Dim tmpstream As StreamReader = File.OpenText(strfilename)
Dim strrecords() As String
Dim strfields() As String
'Load content of file to strLines array
strrecords = tmpstream.ReadToEnd().Split(vbCrLf)
' Redimension the array.
num_rows = UBound(strrecords)
ReDim strarray(num_rows, 2)
' Copy the data into the array.
For x = 0 To num_rows - 1
strfields = strrecords(x).Split("|")
For y = 0 To 1
strarray(x, y) = strfields(y)
Next
Next
' Display the data in listbox
For x = 0 To num_rows - 1
Dim tbxname As String = strarray(x, 0)
tbxname = Remove(tbxname) 'routine that removes invisible characters
tbxname = "tbx" & tbxname
MsgBox(tbxname) 'used to verify each file and which one fails
Me.Controls(tbxname).Text = strarray(x, 1)
Next
Else : MsgBox("File doesn't exist!")
End If
End Sub
I hope that's enough information. Thanks in advance for any help!!

I think the line Me.Controls(tbxname).text = strarray(x,1) does not address your TextBox in your tab control, you may need to find out how to address your textbox in the tab page.
Something like
Me.TabControl1.TabPages(0).Controls(tbxname).text = starray(x,1)

Related

How to match last line of text file in treeview and display text boxes in vb.net?

I have a problem with a sorted TreeView. I select the last line of a text file, then I extract from this text file the last child node added in the TreeView. Where the shoe pinch is that I can't do it! I have tried with the number of lines in this file, but no results. In fact, I do a bit of everything (not of course) to get the selected node to coincide in the treeview and the displays in the text boxes. Below is a screenshot and my code! I don't know if I made myself understood correctly, my English is translated English. Thank you. Claude.
Dim NbLine As Integer = 0
Dim SR As System.IO.StreamReader = New System.IO.StreamReader(OuvrirFichier)
While Not SR.EndOfStream
SR.ReadLine()
NbLine += 1
End While
SR.Close()
Dim lastLine As String = File.ReadLines(OuvrirFichier, Encoding.UTF8) _
.Where(Function(f As String) (Not String.IsNullOrEmpty(f))).Last.ToString
Dim mytext As String = lastLine.Substring(17, 90)
If NbLine > 0 Then
Dim lignesDuFichier As String() = File.ReadAllLines(OuvrirFichier, Encoding.UTF8)
Dim derniereLigne As String = lignesDuFichier(lignesDuFichier.Length - 1)
TreeView1.Focus()
TreeView1.SelectedNode = TreeView1.Nodes(0).Nodes(lignesDuFichier.Length - 1)
End If
Comments in line.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim OuvrirFichier = "C:\Users\maryo\Desktop\Code\Test Empty Line.txt" '"path to file"
'At least you will only be reading the file once
Dim AllLines = File.ReadAllLines(OuvrirFichier)
Dim LinesWithContent = AllLines.Where(Function(s) s.Trim() <> String.Empty)
Dim lastLine = LinesWithContent.Last
Dim mytext As String = lastLine.Substring(17, 90)
Debug.Print(mytext) 'Just checking that you get what was expected
Dim NbLine = AllLines.Length
Dim derniereLigne As String = AllLines(NbLine - 1) 'Another variable to hold last line???
'But this time it could be a blank line.
TreeView1.Focus()
'This makes no sense. An index of a subNode base on the number of lines in the text file
'is supposed to be the SelectedNode
'Why would this be the last node added?
TreeView1.SelectedNode = TreeView1.Nodes(0).Nodes(NbLine - 1)
'You never test the equality of the SelectedNode with mytext
End Sub

Load textfile containing names to a textbox

I am attempting to load a text file that contains a list of names into a text box using a button on the form. Also, I would like to display the following name after the button is pressed. I have been trying to successfully implement this code for several days however, my program loads all names at once. Would anyone be able to provide advice about loading text files?
Below is a copy of my code:
firstName.Multiline = True 'Variable contains first name.
lastName.Multiline = True 'Variable contains last name.
Dim fullName = "" 'Variable containing full name found in text file
Dim lines = IO.File.ReadAllLines("input.txt") 'loading input file located in Debug folder.
For Each i As String In lines
Dim fullNames = lines.Where(Function(line) line.Contains(" "))
If fullNames.Any() Then
Dim fullNamesSplit = fullNames.Select(Function(line) line.Split(" "c))
Dim firstNames = fullNamesSplit.Select(Function(line) line(0))
Dim lastNames = fullNamesSplit.Select(Function(line) line(1))
firstName.Lines = firstNames.ToArray()
lastName.Lines = lastNames.ToArray()
fullName = String.Join(Environment.NewLine, fullNames)
Else
firstName.Text = ""
lastName.Text = ""
End If
displayInfo.Items.Add(fullName)
Next
There's no loop. Load the names into an array, initialise an index variable to 0 and load the name at that index. Each time you click the Button, increment the index and load the name at that index. Once you reach the end, you can either wrap to the beginning or tell the user there are no more names. If you don't want to wrap then an even better option would be to load the names into a queue and then just dequeue on each click.
I have been able to display the names in order however I did not use a looping structure. However, the names are output multiple times in the text box after the button is clicked.
Dim i As Integer = 0
Private Sub NextAvName_Click(sender As Object, e As EventArgs) Handles nextAvName.Click
firstName.Multiline = True 'Variable contains first name.
lastName.Multiline = True 'Variable contains last name.
Dim fullName = "" 'Variable containing full name found in text file
Dim lines = IO.File.ReadAllLines("input.txt") 'loading input file located in Debug folder.
lines = lines.ToArray
Dim element As String
element = lines(i)
Dim fullNames = element.Where(Function(line) element.Contains(" "))
If fullNames.Any() Then
Dim fullNamesSplit = fullNames.Select(Function(line) element.Split(" "c))
Dim firstNames = fullNamesSplit.Select(Function(line) line(0))
Dim lastNames = fullNamesSplit.Select(Function(line) line(1))
firstName.Lines = firstNames.ToArray()
lastName.Lines = lastNames.ToArray()
fullName = String.Join(Environment.NewLine, fullNames)
Else
firstName.Text = ""
lastName.Text = ""
End If
displayInfo.Items.Add(fullName)
i = i + 1

vb.net find textbox name that begins with specified string in a TabControl

I have a TabControl in a form with 4 tabpages. Each tabpage has multiple GroupBox. Each GroupBox has tableLayoutPanel. Each tableLayoutPanel has pragmatically generated array of textbox. if checkbox in a tableLayoutPanel is checked by the user then textboxes in the respective row will be generated. Suppose, the name of one of my textbox array is txtMax(0), txtMax(1).......upto txtMax(42). I need to know how many txtMax(?) (along with their index array) has been generated and become visible. I have tried the the following:
Dim coutGene as integer = 0
Dim coutParameter as integer = 0
Dim indx As Integer
Dim cntl1, cntl2, cntl3 As Control
For Each cnn As TabPage In tabParameters.TabPages
cntl1 = DirectCast(cnn, TabPage)
For Each c2 As Control In cntl1.Controls
If TypeOf (c2) Is GroupBox Then
cntl2 = DirectCast(c2, GroupBox)
For Each c3 As Control In cntl2.Controls
If TypeOf (c3) Is TableLayoutPanel Then
cntl3 = DirectCast(c3, TableLayoutPanel)
For Each c4 As Control In cntl3.Controls
If TypeOf (c4) Is TextBox Then
Dim txt As TextBox = DirectCast(c4, TextBox)
If txt.Name.StartsWith("txtMax") Then
If txt.Visible = True Then
indx = CInt(Between(txt.Name, "(", ")"))
countGene = CInt(countGene + Val(txtGene(indx).Text))
countParameter = countParameter + 1
txtMax(indx).Tag = ""
End If
End If
End If
Next
End If
Next
End If
Next
Next
Function Between(value As String, a As String, b As String) As String
' Get positions for both string arguments.
Dim posA As Integer = value.IndexOf(a)
Dim posB As Integer = value.LastIndexOf(b)
If posA = -1 Then
Return ""
End If
If posB = -1 Then
Return ""
End If
Dim adjustedPosA As Integer = posA + a.Length
If adjustedPosA >= posB Then
Return ""
End If
' Get the substring between the two positions.
Return value.Substring(adjustedPosA, posB - adjustedPosA)
End Function
But the every time code is not getting inside the loop for this condition If txt.Name.StartsWith("txtMax") Then
I am stuck up here. Any assistance will be highly appreciated. Regards. Tariq
You should simplify that code to this:
For Each tp As TabPage In tabParameters.TabPages
For Each gb In tp.Controls.OfType(Of GroupBox)()
For Each tlp In gb.Controls.OfType(Of TableLayoutPanel)()
For Each tb In tlp.Controls.OfType(Of TextBox)().Where(Function(c) c.Visible AndAlso c.Name.StartsWith("txtMax"))
'If you get here, tb is definitely a visible TextBox with a Name starting with "txtMax".
Next
Next
Next
Next
That code will find every visible TextBox with a Name that starts with ""txtMax" inside a TableLayoutPanel, inside a GroupBox, inside a TabPage, inside tabParameters, guaranteed. If that code doesn;t find any such controls, it's because there are no such controls, so that's what you need to investigate.
Thank you for all yours guidelines and suggestion. I tried to implement all,,, but the code could not find the control even though the control exists and visible. I tried this simple code
For k = 1 To 42
If txtMax(k).Visible = True Then
countGene = CInt(countGene + Val(txtGene(k).Text))
countParameter = countParameter + 1
txtMax(k).Tag = ""
End If
Next
But i find that, it search and count the control that exists only in the present tabpage of the TabControl. So i modified the code, though not efficient code, to solve my problem.
I have 4 tabpages in the TabControl. So i tried to select each tabpage by its index and searched 4 times.
For tp As Integer = 0 To 3
tabParameters.SelectedIndex = tp
For k = 1 To 42
If txtMax(k).Visible = True Then
countGene = CInt(countGene + Val(txtGene(k).Text))
countParameter = countParameter + 1
txtMax(k).Tag = ""
End If
Next
Next
Though i solved my problem, but still i seek your advise for efficient code.

VB.net update list items from file

I click a button (with this code) to load lines from file "testexam" into a a listbox "lstHere". Testexam will be updated by another program and I want a code to copy new lines of "testexam" to the bottom of "lstHere". Secondly the selected index should come to the first item of the new list. Any help will be greatly appreciated.
Private Sub
Dim MReader As New StreamReader("C:\Users\Sparrow\testexam.txt")
Dim this1 As String = ""
Dim thisline(6000) As String
Dim i As Integer = 0
Do Until MReader.Peek = -1
this1= MReader.ReadLine
thisline(i)= this1
lstHere.Items.Add(thisline(i))
'go to the next line.
i = i + 1
Loop
End Sub
I don't know how you are trying to implement this, but it works with different buttons.
Button1:
'Add the selected item to the top
ListBox1.Items.Insert(0, ListBox1.SelectedIndex)
Button2:
'Delete duplicates
Dim items(ListBox1.Items.Count - 1) As Object
ListBox1.Items.CopyTo(items, 0)
ListBox1.Items.Clear()
ListBox1.Items.AddRange(items.AsEnumerable().Distinct().ToArray())

Adding records (Row/ Column) to DataGridView; Collection already belongs to a DataGridView control VB.NET

I'm looking for some help with an issue I am having.
I have multiple text files, in a folder. The folder can have an "unlimited" amount of text files in it, although typically 2-150 files
http://gyazo.com/5f314d1ca374abf9f813914609dd931d (images for this + below, can't embed due to lack of reputation)
Each file then contains an "unlimited" (although typically 0-20 lines) amount of data inside it. Line 1 being the "test number" and line 2 being the "test result" - as seen in the image above
My Data Grid View has 3 columns in it (Username, test number, test result) - as seen in the image above
When running my code below; first record being added to the Data Grid View works perfectly, but the second (or any record after the first) the error occurs:
http://gyazo.com/0d492b97d918853e62c55ee314f3f181 (image) or error message:
"System.InvalidOperationException: Collection already belongs to a
DataGridView control. This operation is no longer valid. at
System.Windows.Forms.DataGridViewCellCollection.Add(DataGridViewCelldataGridViewCell)
at SpellingBee.TeacherMultiResults.TeacherMultiResults_Load(Object
sender, EventArgs e)"
This error occurs on the DGVRow.Cells.Add(DGVCell) 'add cell to row
One thing I don't want to do is change any of my text file/ folder structures, even though I'm aware that it is currently inefficient storage.
How can I fix this error? I'm using VB.net (Visual Studios 2013)
If you need any more information, please just ask
Many thanks.
Imports System.Windows.Forms
Imports System.IO
Public Class TeacherMultiResults
Dim AmountOfFiles
Dim LineCount As Integer = 0
Dim FileName As IO.FileInfo
Dim DGVRow As New DataGridViewRow
Dim DGVCell As DataGridViewCell
Dim Username As String = ""
Dim TestNumber As Integer = 0
Dim TestResult As Integer = 0
Private Sub TeacherMultiResults_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim directory As New IO.DirectoryInfo(LoadForm.CurrentDirectory & "\UserResults\") 'selects directory
Dim FileNames As IO.FileInfo() = directory.GetFiles()
Dim Files As IO.FileInfo
For Each Files In FileNames 'list the names of all files in the specified directory
Username = Files.ToString
Username = (Username.Substring(0, Username.Length - 4)) 'removes the .txt from the name
Try
LineCount = File.ReadAllLines(LoadForm.CurrentDirectory & "\UserResults\" & Username & ".txt").Length 'amount of lines in file
If LineCount > 1 Then
Dim Information As New System.IO.StreamReader(LoadForm.CurrentDirectory & "\UserResults\" & Username & ".txt") 'opens file
LineCount = LineCount / 2 'halfs line count
For i = 0 To LineCount - 1
TestNumber = Information.ReadLine() 'reads line to variable
TestResult = Information.ReadLine() 'reads line to variable
i = i + 1 'adds one to i
DGVCell = New DataGridViewTextBoxCell 'create a new DGV text box cell
DGVCell.Value = Username 'add value to DGV text box cell
DGVRow.Cells.Add(DGVCell) 'add cell to row
DGVCell = New DataGridViewTextBoxCell 'create a new DGV text box cell
DGVCell.Value = TestNumber 'add value to DGV text box cell
DGVRow.Cells.Add(DGVCell) 'add cell to row
DGVCell = New DataGridViewTextBoxCell 'create a new DGV text box cell
DGVCell.Value = TestResult 'add value to DGV text box cell
DGVRow.Cells.Add(DGVCell) 'add cell to row
DGV_MultiResults.Rows.Add(DGVRow) 'add row to DGV
Next
Information.Close() 'Close read
End If
Catch ex As Exception 'if file won't read
MsgBox(ex.ToString) 'show error
Exit Try
End Try 'end of try
Next 'end of files
End Sub
I hope that somebody can help me with this issue, I understand it's fairly simple to fix most probably although I can't seem to find a solution to the error!
Many thanks, Toby.
When working with a DataGridView, it is generally easier to just build an object list and then bind it to the DGV using the built-in data binding features.
For your example, it would look like this:
' Read the files, build objects as you go and add them to a list
Dim lst = New List(Of TeacherMultiResults)
' Replace this part with your file reading code...
Dim t1 = New TeacherMultiResults With {.Username = "Bob", .TestNumber = 1, .TestResult = 75}
lst.Add(t1)
Dim t2 = New TeacherMultiResults With {.Username = "Rick", .TestNumber = 1, .TestResult = 85}
lst.Add(t2)
Dim t3 = New TeacherMultiResults With {.Username = "Zoe", .TestNumber = 1, .TestResult = 95}
lst.Add(t3)
' Bind the list to the DataGridView
Dim bindList = New BindingList(Of TeacherMultiResults)(lst)
Dim bindSrc = New BindingSource
bindSrc.DataSource = bindList
grid.DataSource = bindSrc
Your grid should display each item of your list.