TextBox writing on one line only - vb.net

When ever I type something IN a textbox, than I click the button, I have a writeline. Is there a way to assign that one text box to only the first line, and the second text box to the second line on a notepad? So when you type something new in it, it will delete what you previously had on the first line, than add the new thing in the text box?
I am using.
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("C:/Users/Nick/Documents/Dra.txt", True)
file.WriteLine(NameBasic)
file.WriteLine(LastBasic)
file.Close()

Second argument in OpenTextFileWriter() method is append. It means that strings will be appended to the end of the file if it get True value.
Try to use False instead:
file = My.Computer.FileSystem.OpenTextFileWriter("C:/Users/Nick/Documents/Dra.txt", False)
UPD
Dim read As String = Console.ReadLine()
Dim num As Integer
Integer.TryParse(read, num)

Related

How to search only the first line of a multiline textbox in VB.NET

Is there any way to search only the first line of a Multiline Textbox without knowing exactly at what position the text is you're looking for?
If I knew the position of the text I was looking for I could do something like:
Dim myNotes As String = "The book has a lot of text"
Dim myText As String = "text"
If Not myNotes.Substring(0,4) = myText Then
' Do Something
End If
Or if I wanted to search the entire textbox I could do something like:
Dim myNotes As String = "The book has a lot of text"
Dim myText As String = "text"
If Not myNotes.Contains(myText) Then
' Do Something
End If
But I want to search only the first line of the textbox and I'm not sure at what position the text may be. Is there anyway to do a search like that?
This is another example of why you should ALWAYS read the relevant documentation. If you had read the documentation for the TextBox class then you'd know that it has a Lines property. To get the first line of text, you simply get the first element of that array:
Dim firstLine = myTextBox.Lines(0)
If Not filrstLine.Contains(myText) Then
'Do something
End If
Note that this only applies where the user has explicitly added a line break to the text. I assume that that is what you want, given that you have accepted another answer that does the same thing. If you mean the first line based on automatic word-wrap then that requires a bit more effort.
You could take the text and extract the first line.
int pos = text.IndexOfAny('\r', '\n');
if (pos >= 0)
text = text.SubString(0, pos);
// text now contains only the first line
Then you can search the resulting string.

Deleting all lines in text file until you get to a word vb.net

Very new to vb.net, apologies if this is basic. I am trying to open up a text file and delete all the lines starting at index 0 until I hit the line that has the word I am looking for. Right now, it just deletes the word I put in it.
' Read the file line by line
Using reader As New IO.StreamReader(fileName)
While Not reader.EndOfStream()
Dim input As String = reader.ReadLine()
'Delete all lines up to String
Dim i As Integer
i = 0
For i = 0 To input.Contains("{MyWord}")
builder.AppendLine(input)
Next
End While
End Using
Partial. You didn't say what to do with the rest of the lines...
Did you mean lines?
Dim ShouldRead as Boolean
Dim builder As New System.Text.StringBuilder
Using reader As New IO.StreamReader(fileName)
'Delete all lines without String
While Not reader.EndOfStream()
Dim input As String = reader.ReadLine()
If input.Contains("{MyWord}") Then ShouldRead = True
If ShouldRead Then
builder.AppendLine(input)
End If
End While
End Using
I would tend to do it like this:
Dim lines = File.ReadLines(filePath).
SkipWhile(Function(line) Not line.Contains(word)).
ToArray()
File.WriteAllLines(filePath, lines)
The File.ReadLines method reads the lines of the file one by one and exposes them for processing as they are read. That's in contrast to the File.ReadAllLines method, which reads all the lines of the file and returns them in an array, at which case you can do as desired with that array.
The SkipWhile method will skip the items in a list while the specified condition is True and expose the rest of the list, so that code will skip lines while they don't contain the specified word and return the rest, which are then pushed into an array and returned. That array is then written back over the original file.
Just note that String.Contains is case-sensitive. If you're using .NET Core 2.1 or later then there is a case-insensitive overload but older versions would require the use of String.IndexOf for case-insensitivity.

Trying to close textfile after line is read

Im trying to output the data from the second line of my textfile to a datagridview but when doing so it is also outputting every line after the the second line. This is what I have tried. Thanks
Dim lines = IO.File.ReadAllLines(OrderID & ".txt")
For index = 1 To lines.Length - 1
Dim cells = lines(index).Split(","c)
dgvOutput.Rows.Add(cells)
FileClose()
It's outputting every line after the second line, because that's what you're telling it to do when you iterate through the array of strings returns from ReadAllLines.
IO.File.ReadAllLines does not leave an output stream open. The file is closed. What it does do, is return a zero-based (by default) array of the contents of the file, with line breaks being the delimiter for the split.
To just get the contents of the second line, using ReadAllLines, this is what you need:
Dim lines = IO.File.ReadAllLines(OrderID & ".txt")
If lines.length >= 2 Then
Dim cells = lines(1).Split(","c)
dgvOutput.Rows.Add(cells)
End If
Now, that does have the overhead of reading the entire file in. If you open the file using a reader object, then you only need to read the first and second lines of the file to get that second line.
That would be something like this:
Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(OrderId & ".txt")
Dim a as String
' This reads the first line, which we throw away
reader.ReadLine()
a = reader.ReadLine()
reader.Close()
Dim cells = a.Split(","c)
dgvOutput.Rows.Add(cells)
You would need to test your explicit circumstances to determine which is better for what you're trying to do.
Your loop is executed over all lines skipping just the first line.
While I cannot see what happen in the FileClose call it seems to not have any sense because ReadAllLines has already closed the file.
You can get the second line of your file with a single line of code
Dim line as String = File.ReadLines(OrderID & ".txt").Skip(1).Take(1).FirstOrDefault()
' this check is required to avoid problems with files containing 0 or 1 line
if line IsNot Nothing Then
Dim cells = line.Split(","c)
dgvOutput.Rows.Add(cells)
End If
Notice that I have replaced the ReadAllLines with ReadLines. This is better because using this method you don't read all lines when you need only the second one (if it exists). More info at ReadLines vs ReadAllLines
Dim lines = IO.File.ReadAllLines(OrderID & ".txt")
Dim SecondLine = lines(1)
File.ReadAllLines opens and closes the file for you so there is not need to add code to close it.

VB.net load controls and content from textfile to textboxes

...Hopefully this question will be readable...
I have 27 textboxes.
The controlname and the text in the textboxes are written to a textfile like this:
System.DateTime.Now.ToString("yyyyMMdd") & "_Names_Config.txt"
Dim objWriter As New System.IO.StreamWriter(configfile, True)
'Textboxes
objwriter.Writeline("tbmax1") 'Control name
objwriter.Writeline("tbmax1.text) 'The text in the textbox
objWriter.WriteLine("tbname1") 'Control name
objWriter.WriteLine(tbname1.Text) 'The text in the textbox
objWriter.WriteLine("tbext1") 'Control name
objWriter.WriteLine(tbext1.Text) 'The text in the textbox
'And so on for all the the controls
This goes on for all the textboxes and controls, so 54 lines in total.
Works great. The textfile looks like this:
Alright, now the issue. There will be a load button that should search the textfile -> find the control matching the form's control -> use the line below and fill that spesific line in the control's textbox -> then find next control and do the same.
Load button: This is #1 attempt;
'Openfiledialog, then:
Using reader As New StreamReader(OpenFileDialog1.FileName.ToString)
Dim currentTextBox As TextBox = Nothing
While reader.Peek > -1
Dim line As String = reader.ReadLine()
If Not String.IsNullOrEmpty(line) Then
Dim tmpTextbox = Controls.Find(line, True) 'Try to find text according to line
If tmpTextbox.Any() Then 'It´s a textbox name
currentTextBox = DirectCast(tmpTextbox(0), TextBox)
Else
'?
End If
End If
End While
End Using
Here comes what I don't understand at all. See before and after picture of what happens to the 27 textboxes after I load the textfile.
What it SHOULD look like:
What it will look like:
"Edit channels" is actually the title of the form itself. I'm speechless. Because I totally don't understand why this happens and the load code, I moved on to another attempt.
#2 attempt:
Using reader As New StreamReader(OpenFileDialog1.FileName)
Dim Line As String = reader.ReadLine()
Dim Current As Integer = 0
Dim TB As TextBox = Nothing
While Not IsNothing(Line) 'It will be Nothing when file is over
'__________________________________________________________________1
If Line.StartsWith("tbext1") Then
'We will increment CurrentChannel, as we changed the section
Current += 1
For onetonine = 1 To 9
tbext1.Text = Line
Next
End If
If Line.StartsWith("tbname1") Then
'We will increment CurrentChannel, as we changed the section
Current += 1
For onetonine = 1 To 9
tbname1.Text = Line
Next
End If
If Line.StartsWith("tbmax1") Then
'We will increment CurrentChannel, as we changed the section
Current += 1
For onetonine = 1 To 9
tbmax1.Text = Line
Next
End If
'__________________________________________________________________2
'Then I guess this would go on for all the 27 textboxes (probably a really bad attempt)
End While
End Using
However, this just goes into break mode.
Your first approach works already if you fill the Else part:
If tmpTextbox.Any() Then
currentTextBox = DirectCast(tmpTextbox(0), TextBox)
ElseIf currentTextBox IsNot Nothing Then
currentTextBox.Text = line
End If
But you should not use it in production code:
Control-names are a very bad key for a database record or file entry:
They can change in future and you won't notice it
They are GUI related and not supposed to be identifiers for properties
is not fail-safe because there could be multiple controls with the same name
don't store key-value pairs on different lines, that makes it difficult, less readable and more error-prone to put them together afterwards
If you want to use one line you need a delimiter that a user never enters, it can be a combination of multiple characters like |::| or something similar. Then you can later use String.Split({"|::|"}, StringSplitOptions.None) to get both tokens back.
However, this is still not a good approach and also not 100% safe. So better approaches were
serialize/deserialize a List(Of String).
If you want to store it in a way that a human can read you should prefer XML.
Here's an example how you can write/read xml easily:
' write all TextBoxes to a file '
Dim allTextBoxes = TextBoxPanel.Controls.OfType(Of TextBox)()
Dim doc As New XDocument(New XElement("Channels"))
For Each txt In allTextBoxes
doc.Root.Add(New XElement(txt.Name, txt.Text.Trim()))
Next
doc.Save(OpenFileDialog1.FileName)
' later read it ... '
Dim xml As XDocument = XDocument.Load(OpenFileDialog1.FileName)
For Each element As XElement In xml.Descendants("Channels").Descendants()
Dim txt = allTextBoxes.FirstOrDefault(function(t) t.Name = element.Name)
If txt IsNot nothing
txt.Text = element.Value
End If
Next

Reading a .dat file

I have a file I am trying to read and disply results into a text box. The file has no extension, but it is a 'data' file per the website (www.checkfiletype.com).
Here is a screen shot of how the file looks in a online reader, it looks like hex?
I have tried a stream reader, and gives nothing in results. Last method I tried was a BinaryReader, that I have never used before. The results from this is a "0" into the text box. Given that I have never used the BinaryReader function, I am sure I did something wrong with it.
Using reader As New BinaryReader(File.Open("C:\Users\jefhill\Desktop\CMOSDATA", FileMode.Open))
Dim pos As Integer = 0
Dim length As Integer = reader.BaseStream.Length
While pos < length
' Read the integer.
Dim value As Integer = reader.ReadInt32()
' Write to screen.
TextBox1.Text = value
' Add length of integer in bytes to position.
pos += 4
End While
End Using
Any help would be greatly appreciated.
EDIT
I tried using a basic StreamReader. With this, nothing happens, as in no errors, just puts nothing(blank) into the textbox.
Dim file As String = "C:\Users\jefhill\Desktop\CMOSDATA"
Dim reader As New System.IO.StreamReader(file)
TextBox1.Text = reader.ReadToEnd
reader.Close()
The file is not a text file, and cannot be directly displayed in a TextBox. You will need to find the format of the file and convert it to text in order to display it in a TextBox.