Reading Textbox & 'Grabbing' Line into String Variable vb - vb.net

Okay, I have a textbox, which contains an IP Address, the texbox is populated by a remote file which IS NOT stored - it's downloaded into memory and then placed in the texbox, so it has no actual file in the systems directories, leaving me unable to use the FileStream method.
So, I want to take the text from textbox1, and look for the word 'IP', once this is found I want it to 'grab' that particular line and place it into another textbox (texbox2). How can I do this?
-Please note, there will only ever be ONE line with the word 'IP' in it, and it will always be the first word on the line.

One way...
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
TextBox2.Text = TextBox1.Lines.Where(Function(x) x.ToUpper.StartsWith("IP")).FirstOrDefault
End Sub

Another way is to use indexof to find where the IP text starts
Dim sresult = TextBox1.Text.IndexOf("IP")
Dim linebreak = TextBox1.Text.IndexOf(vbCrLf, sresult)
TextBox2.Text = TextBox1.Text.Substring(sresult, linebreak - sresult)

Related

Why Is A FilePath Item With ~$ Added To ListBox

I am adding file paths from a folder to a List Box which are then opened as text in a Rich Text Box. I have used the same syntax as the code below for achieving the same purpose in another List Box and it works just fine. But, in the current example, I have two files in the default MyProjects folder (i.e. default folder is created by my app), but when I add the file paths from the folder as items to the List Box, I get a third item with ~$ in the file path? This item is obviously some kind of repetition of the first file path in the list? The two files in the default folder are also created by my app so, if this is a file access issue, I don't understand why I wouldn't have access to a file created by my app? Can anyone give me a clue what's happening here?
What I have Tried:
I have tried debugging to check where the extra file path is coming from. As far as I can tell, it is being created when I add the file paths to the List Box? i.e. commenting out the code for adding the items to the List Box stops all items being added, but doesn't tell me where this extra item is coming from?
The "Extra Item" Issue:
System.Windows.Forms.ListBox+ObjectCollectionC:\Users\username\Documents\MySolution\MyProjects\RTFdoc.rtf
C:\Users\username\Documents\MySolution\MyProjects\Testdoc.rtf
C:\Users\username\Documents\MySolution\MyProjects~$Fdoc.rtf
The Code:
lbxName.Items.AddRange(Directory.GetFiles("C:\Users\" + username + "\Documents\MySolution\MyProjects"))
lbxName.SelectedIndex = 0
Code For Loading:
For Each item In lbxName.SelectedItems
RTB.LoadFile(lbxName.SelectedItem, RichTextBoxStreamType.RichText)
Next
I cannot reproduce the error in the following code.
Private Sub FillListBox()
ListBox1.Items.AddRange(Directory.GetFiles("C:\Users\" & username & "\Documents\MySolution\MyProjects"))
ListBox1.SelectedIndex = 0
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FillListBox()
End Sub
Please read the comments in the following code.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each item In ListBox1.SelectedItems
'The following will overwrite the contents of the RichTextBox on each iteration
'This overload of LoadFile will only handle .rtf files
RichTextBox1.LoadFile(item.ToString)
Next
End Sub
I suggest you set the SelectionMode property to One in the designer and do the following.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
RichTextBox1.LoadFile(ListBox1.SelectedItem.ToString)
End Sub
Try to use as follows:
Directory.GetFiles("C:\Users\" & username & "\Documents\MySolution\MyProjects").Where(Function(f)
Return New IO.FileInfo(f).Attributes & IO.FileAttributes.Hidden & IO.FileAttributes.System = 0

How to check a text box for a certain character and replace with a different string in the same spot

I am working on a little morse code translation project and I cannot figure out how to detect when a certain key is in a textbox and replace it with the corresponding morse code dots and dashes in the correct spot.
For example if you type in "a b c" then i would like the program to check and put
".- -... -.-."
but it also needs to be dynamic so if you change up the order of your letters it can update the translation.
as of right now i have a key checking system where you can only type in one forward line and if you mess up you have to clear the whole box. thank you!
Here is a basic example of what I was suggesting in my comments above, i.e. using two separate TextBoxes and translating the whole text every time:
Private morseCodeDictionary As New Dictionary(Of Char, String) From {{"a"c, ".-"},
{"b"c, "-..."},
{"c"c, "-.-."}}
Private Sub inputTextBox_TextChanged(sender As Object, e As EventArgs) Handles inputTextBox.TextChanged
outputTextBox.Text = String.Join(" ",
inputTextBox.Text.
ToLower().
Select(Function(ch) morseCodeDictionary(ch)))
End Sub
Here's an implementation that doesn't use LINQ, so may be more understandable:
Private Sub inputTextBox_TextChanged(sender As Object, e As EventArgs) Handles inputTextBox.TextChanged
Dim characterStrings As New List(Of String)
For Each ch As Char In inputTextBox.Text
characterStrings.Add(morseCodeDictionary(ch))
Next
outputTextBox.Text = String.Join(" ", characterStrings)
End Sub

How do I set the Richtextbox.rtf to a rich text string?

I am trying to add a header to the rich text in a RichTextBox, using VB.NET and Visual Studio 2017. According to the documentation, Richtextbox.rtf should allow me to get or set the rich text including control codes. However, I am unable to set *.rtf to a string containing rich text. I know that the rich text is correct because if I paste it into a *.rtf file, it is displayed correctly.
The test code looks like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim hdr As String = "{\header This is a header}"
Dim s As String = RichTextBox1.Rtf
s = s.Insert(s.LastIndexOf("}"c) - 1, hdr)
MsgBox(s)
With RichTextBox1
RichTextBox1.Rtf = s
MsgBox(RichTextBox1.Rtf)
End With
End Sub
The string s is correctly formatted as rich text, but RichTextBox1.Rtf is unchanged after the assignment. What am I missing? If I can't assign RichTextBox1.Rtf this way, is there an alternative?
Thanks again #PerpetualStudent!
The problem appears to be that the RichTextBox1.RTF field does not accept the "{\header This is a header}" control code. That is probably by design because a RichTextBox cannot display a header. I tried putting the control code in a different location in the rich text string, but that didn't work either.
I can edit the rich text in other ways (see below), but I cannot insert the header control code. That's unfortunate because it is part of the rich text standard. Anyhow, now that I know what the problem is, I can come up with a solution. A workaround might be to modify the print and save code of my rich text box print control form to add the header and footer in the print or save actions.
This works:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
With RichTextBox1
Dim s As String = .Rtf
s = s.Replace("Hello", "Good morning")
MsgBox(s)
.Rtf = s
MsgBox(.Rtf)
End With
End Sub

Equals Not Working VB.Net

I am trying to compare two strings that I know are equal to each other, but it is always skipping to the else. I've tried everything, .Equals, =, IsNot, they all don't work! The frustrating part is that I know the strings are equal! Please take a look at my code and see if it there is possible anything wrong with it.
Public Class Form1
Dim log As String
WithEvents xworker As New System.ComponentModel.BackgroundWorker
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
xworker.RunWorkerAsync()
End Sub
Private Sub xWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles xworker.DoWork
Dim qWorker = CType(sender, System.ComponentModel.BackgroundWorker)
Dim client As New Net.WebClient
log = client.DownloadString("http://########/log.txt")
End Sub
Private Sub xWorker_Completed(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles xworker.RunWorkerCompleted
If log.Equals(RichTextBox1.Text) Then
xworker.RunWorkerAsync()
Else
RichTextBox1.Text = log
xworker.RunWorkerAsync()
End If
End Sub
End Class
You needed to listen to #SLaks and #Hans Passant, they were right on the money.
I setup your code sample and it worked correctly if the source log.txt file didn't have a line terminator in it. Once I added the line terminator I got the results your are getting.
From the command window:
>? RichTextBox1.Text.Length
14
>? log.length
15
Using the QuickWatch window, and TABing until the Value field was selected:
Log result:
"log test 1234" & vbCrLf & ""
RichTextBox result:
"log test 1234" & vbLf & ""
The fix to the problem depends on what will actually get written to the log.txt file. I assume that "log test 1234" is just development code. If you are only interested in a single line as a result code then make sure you are not writing a line terminator. If your result codes are more complicated then you will need to do more parsing on the result than just an Equals compare.
Try this instead.
If log.ToLower().Trim() = RichTextBox1.Text.ToLower().Trim() Then
I think this is case sensitve compare. You should convert both of the strings to upper or to lower and then compare them
If Log.ToLower() = RichTextBox1.Text.ToLower() Then
Or you can use String.Compare method and set third param to true to ignore case
If String.Compare(log, RichTextBox1.Text, True) = 0 Then
I've read that the RichTextBox can change line endings when Text gets set. So the Text property might be returning a string that is different than what was set. I haven't been able to verify, but you can probably devise a quick test of this theory.

How to save the as I type in a textbox

I'm trying to make a textbox where the user inputs a string like "Joe was here" and that same string is "written" on the text file at the same time. Most of the questions asked around is using a button that helps save the string to the text file.
It works great, however for some unknown reason the text file can't register the last key pressed. In other words if I wrote "Joe was here" in my textbox, the text file has "Joe was her" where the "e" is missing.It's always the last key :(
This is a general view of the code I have that makes it work
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
Dim File_name As String = "path where text file is saved at"
If System.IO.File.Exists(File_name) Then
Dim objWriter As New System.IO.StreamWriter(File_name)
objWriter.Write(TextBox1.Text)
objWriter.Close()
End If
End Sub
Maybe I'm missing something? Perhaps I'm using the wrong type of event as I'm using keypress instead of keydown or something else?
i just did a quick sample with your code and gives the exact issue, so i changed to the event keyup and it worked.
reason could be the time that keypress event processes or receives the key code at least in keyup first receive all the text and then executes the call to the process.
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
My.Computer.FileSystem.WriteAllText("C:\test.txt", TextBox1.Text, False)
End Sub