trying to output more than one filenam into textbox vb.net - vb.net

Apologies if this is really simple but I'm fairly new to programming. I've created a program that uses an open dialog box and outputs the names of the file to a textbox.
Where I'm having issues is trying to get the textbox to display more than one line as all it seems to be doing is writing one line in the textbox.
The code I'm using is below, could someone please advise what I need to change so that I can get this to work.
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim strFileName As String
OpenFD.Multiselect = True
OpenFD.InitialDirectory = "\\server\filename\"
OpenFD.Title = "Open a Text File"
OpenFD.Filter = "Text Files(.txt)|*.txt"
Dim DidWork As Integer = OpenFD.ShowDialog()
strFileName = OpenFD.FileName
If DidWork = DialogResult.Cancel Then
MsgBox("Cancel Button Clicked")
Else
strFileName = OpenFD.FileName
TextBox1.Text = strFileName += 1
End If
End Sub
I've managed to get everything else to work correctly but it's just this one thing.

Dim strFileName() As String
'...
Dim DidWork As Integer = OpenFD.ShowDialog()
If DidWork = DialogResult.Cancel Then
MsgBox("Cancel Button Clicked")
Else
strFileName = OpenFD.FileNames
TextBox1.Multiline = True
TextBox1.Text = ""
For Each sFile as String in strFileName
TextBox1.Text &= sFile & System.Enviroment.NewLine()
Next
End If

Set TextBox.Multiline property to True

Related

Opening a file from List View?

This is my first question on the site and I am fairy new at how code works. I need to be able to open a file from a list view. I can get the file path to open up my file explorer, but can not get it to directly open the selected file. It gives me an error saying "System.ComponentModel.Win32Exception: 'The system cannot find the file specified" I've checked the file path from my file explorer and the path it pulls from and they both seem to match. Here is an example of what I've written.
Private Sub ListView1_Function(sender As Object, e As EventArgs) Handles ListView1.ItemSelectionChanged
If Not ListView1.SelectedItems.Item(0).Text = "" Then
For Each ListViewItemVar As ListViewItem In ListView1.Items
Dim filePath As String = $"C:\Users\{My.User.Name.Split("\").ElementAt(1)}\S & J Tube Inc\Files_Storage - Documents\Shipping Wizard\"
Dim selectedFile As String = ListViewItemVar.Text
If ListViewItemVar.Selected = True Then
If MessageBox.Show("You are about to open " & filePath & ". Are you sure?", "Open File", MessageBoxButtons.YesNo, MessageBoxIcon.Information) = DialogResult.Yes Then
Process.Start(filePath + selectedFile)
ElseIf DialogResult.No Then
MsgBox("You decided not to open the file.")
End If
End If
Next
End If
End Sub
You have to use ListView1_ItemActivate
1.Create a project with Form with ListView1 and Label1 controls on it
2.Replace yourName in dirInfo with your name from Users\eee\Documents
And all the code you need is :
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'CreateHeadersAndFillListView
ListView1.View = View.Details
ListView1.Columns.Add("Filename")
ListView1.Columns.Add("Size")
ListView1.Columns.Add("Last accessed")
Dim dirInfo As New DirectoryInfo("C:\Users\yourName\Documents")
Dim fileInfo As FileInfo
Dim lvi As ListViewItem
Dim lvsi As ListViewItem.ListViewSubItem
For Each fileInfo In dirInfo.GetFiles("*.*")
lvi = New ListViewItem With {
.Text = fileInfo.Name,
.ImageIndex = 1,
.Tag = fileInfo.FullName
}
lvsi = New ListViewItem.ListViewSubItem With {
.Text = fileInfo.Length.ToString()
}
lvi.SubItems.Add(lvsi)
lvsi = New ListViewItem.ListViewSubItem With {
.Text = fileInfo.LastAccessTime.ToString()
}
lvi.SubItems.Add(lvsi)
ListView1.Items.Add(lvi)
Next
'after populating the list this will size columns to the width of column data
ListView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
Label1.Text = "C:\Users\yourName\Documents" + Environment.NewLine + " (Double click to open file !)"
AddHandler ListView1.ItemActivate, AddressOf ListView1_ItemActivate
End Sub
Private Sub ListView1_ItemActivate(sender As Object, e As System.EventArgs)
Dim filename As String = ListView1.SelectedItems(0).Tag.ToString()
Try
Process.Start(filename)
Catch
Return
End Try
End Sub

Search through text file and return a line of text

I am trying to create a program that will search a text file for a line of text and then return the full line of information.
Example line: Joe Blogs JBL 1234
Search: Joe Blogs
Search returns: Joe Blogs JBL 1234
To make it as simple as possible, I have 2 text boxes & 1 button.
Textbox1 = search
Textbox2 = Search results
Button = Search button
Can anyone tell me how to do this because I'm finding it really difficult. I'm new to VB coding so the simplest of code would be helpful!
This is what I have so far:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Input Text Error
If TextBox1.TextLength = 0 Then
MsgBox("Please enter a Staff Name or Staff Code", MsgBoxStyle.Information, "Error")
End If
'Perform Search
Dim strText As String = SearchFile("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt", TextBox1.Text)
If strText <> String.Empty Then
TextBox2.Text = strText
End If
End Sub
'Search Function
Public Shared Function SearchFile(ByVal strFilePath As String, ByVal strSearchTerm As String) As String
Dim sr As StreamReader = New StreamReader(strFilePath)
Dim strLine As String = String.Empty
Try
Do While sr.Peek() >= 0
strLine = String.Empty
strLine = sr.ReadLine
If strLine.Contains(strSearchTerm) Then
sr.Close()
Exit Do
End If
Loop
Return strLine
Catch ex As Exception
Return String.Empty
End Try
End Function
'Clear Button
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TextBox2.Text = ""
TextBox1.Text = ""
End Sub
' Open The text file
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Process.Start("C:\Users\kylesnelling\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt")
End Sub
End Class
Whenever I perform a search, all I get back is the last line of the text file... does anyone know why?
As Alex B has stated in comments, line If strLine.Contains("textbox1.text") should be If strLine.Contains(strSearchTerm)
Also you are not passing in the search item to the function. The below line you have passed in the string textbox1.text as a string rather than the text inside the textbox. Hence why you never find the line you are searching for and always returns the last record of your file.
Dim strText As String = SearchFile("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt", "textbox1,text")
This line should be:
Dim strText As String = SearchFile("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt", textbox1.text)
Also with this line Dim sr As StreamReader = New StreamReader("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt") why have you used the same path destination when you have already passed in this file location in the variable strFilePath.
line should be Dim sr As StreamReader = New StreamReader(strFilePath)
Its best to use the variables being passed into the function otherwise this function won't be very useful to other parts of code that may be referencing it or if search terms or filepaths change.
Updated from comments:
strLine.ToUpper.Contains(strSearchTerm.ToUpper) this line will make both text uppercase and the word you are searching for to uppercase, which will allow them to ignore case sensitivity, so for example, "text" can match with "Text" by both being converted to "TEXT" when used to compare.
Give this a try friend.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim searchResult As String = SearchFile("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt", _
"text to search for")
Me.TextBox2.Text = searchResult
End Sub
Public Shared Function SearchFile(ByVal strFilePath As String, ByVal strSearchTerm As String) As String
Dim fs As New System.IO.StreamReader(strFilePath)
Dim currentLine As String = String.Empty
Try
Dim searchResult As String = String.Empty
Do While fs.EndOfStream = False
currentLine = fs.ReadLine
If currentLine.IndexOf(strSearchTerm) > -1 Then
searchResult = currentLine
Exit Do
End If
Loop
Return searchResult
Catch ex As Exception
Return String.Empty
End Try
End Function

Textbox replace and split not working vb.net

I've been struggling way too much with simple things, like the one i'm posting.
I'm developing a UI in vb.net that gathers some information from a machine. The information is collected to a TextBox:
Private Sub ReceivedText(ByVal [text] As String)
If Me.TextBox2.InvokeRequired Then
Dim x As New SetTextCallBlack(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.TextBox2.Text &= [text]
End If
End Sub
Then i gather that information either to a datagridview or to some labels to display simple information.
Sub dgv()
Dim sup2 = TextBox2.Text.Replace("#", "").Replace(">", " "c)
Dim sup() = sup2.Split(" "c, "#", vbCrLf, vbTab)
With DataGridView1
.Rows(0).Cells(0).Value = sup(1).ToString
.Rows(0).Cells(1).Value = sup(7).ToString
.Rows(0).Cells(3).Value = sup(4).ToString
End With
Button5.Enabled = True
Button6.Enabled = True
End Sub
This works just fine !!!
But when i try to populate the labels, with the code below, it just won't work!
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Thread.Sleep(250)
Dim final = TextBox2.Text.Replace("#", "").Replace("SN", " "c)
Dim final2() = final.Split(" "c, "#", vbCrLf, vbTab)
Label1.Text = final2(0).ToString
Textbox2.Text= final2(0).ToString
End Sub
Can someone help me? The label gets no text.. and the textbox gets all of it.
Btw, the textbox is multiline and if i paste the text in microsoft word it comes with tabs and extra spaces.
Edit: printscreen from microsoft word below [ related to Multiline Textbox to Datagridview ]
Edit2: This is so strange ..
If i do this
Label1.Text = "Testing" & TextBox2.Text
it only shows "Testing" on the label..
If you set the label to AutoSize, it will automatically grow with whatever text you put in it. (This includes vertical growth.)
Before assign value to the label1,
Use the below code
Label1.MaximumSize = new Size(100, 0)
Label1.AutoSize = true
your code would be like
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Thread.Sleep(250)
Dim final = TextBox2.Text.Replace("#", "").Replace("SN", " "c)
Dim final2() = final.Split(" "c, "#", vbCrLf, vbTab)
Label1.MaximumSize = new Size(100, 0)
Label1.AutoSize = true
Label1.Text = final2(0).ToString
Textbox2.Text= final2(0).ToString
End Sub

Double openDialog VBA

When I try to run this code it opens an open dialog with no results, then it opens another and does what I want it to do. Help?
Private Sub mnuOpen_Click(sender As Object, e As EventArgs) Handles mnuOpen.Click
Dim DidWork As Integer = openFD.ShowDialog()
openFD.InitialDirectory = "C:\"
openFD.Title = "Open a text file"
openFD.Filter = "Text Files|*.txt|Word Docs|*.doc"
openFD.ShowDialog()
If DidWork = DialogResult.Cancel Then
MsgBox("Cancel Button Clicked")
Else
strFileName = openFD.FileName
MsgBox(strFileName)
End If
End Sub
You don't need the DidWork variable in your example (and as pointed out, you are calling ShowDialog twice).
I would favor checking for Ok instead of Cancel in the DialogResult:
openFD.InitialDirectory = "C:\"
openFD.Title = "Open a text file"
openFD.Filter = "Text Files|*.txt|Word Docs|*.doc"
If openFD.ShowDialog() = DialogResult.Ok Then
strFileName = openFD.FileName
MsgBox(strFileName)
Else
MsgBox("Dialog Canceled")
End If

Read Text File and Output Multiple Lines to a Textbox

I'm trying to read a text file with multiple lines and then display it in a textbox. The problem is that my program only reads one line. Can someone point out the mistake to me?
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Public Class Form1
Private BagelStreamReader As StreamReader
Private PhoneStreamWriter As StreamWriter
Dim ResponseDialogResult As DialogResult
Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
'Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
'Is file already open
If PhoneStreamWriter IsNot Nothing Then
PhoneStreamWriter.Close()
End If
With OpenFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
'If ResponseDialogResult <> DialogResult.Cancel Then
' PhoneStreamWriter = New StreamWriter(OpenFileDialog1.FileName)
'End If
Try
BagelStreamReader = New StreamReader(OpenFileDialog1.FileName)
DisplayRecord()
Catch ex As Exception
MessageBox.Show("File not found or is invalid.", "Data Error")
End Try
End Sub
Private Sub DisplayRecord()
Do Until BagelStreamReader.Peek = -1
TextBox1.Text = BagelStreamReader.ReadLine()
Loop
'MessageBox.Show("No more records to display.", "End of File")
'End If
End Sub
Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
With SaveFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
PhoneStreamWriter.WriteLine(TextBox1.Text)
With TextBox1
.Clear()
.Focus()
End With
TextBox1.Clear()
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
PhoneStreamWriter.Close()
Me.Close()
End Sub
End Class
Here is a sample textfile:
Banana nut
Blueberry
Cinnamon
Egg
Plain
Poppy Seed
Pumpkin
Rye
Salt
Sesame seed
You're probably only getting the last line in the file, right? Your code sets TextBox1.Text equal to BagelSteramReader.ReadLine() every time, overwriting the previous value of TextBox1.Text. Try TextBox1.Text += BagelStreamReader.ReadLine() + '\n'
Edit: Though I must steal agree with Hans Passant's commented idea on this; If you want an more efficient algorithm, File.ReadAllLines() even saves you time and money...though I didn't know of it myself. Darn .NET, having so many features...
I wrote a program to both write to and read from a text file. To write the lines of a list box to a text file I used the following code:
Private Sub txtWriteToTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtWriteToTextfile.Click
Dim FileWriter As StreamWriter
FileWriter = New StreamWriter(FileName, False)
' 3. Write some sample data to the file.
For i = 1 To lstNamesList.Items.Count
FileWriter.Write(lstNamesList.Items(i - 1).ToString)
FileWriter.Write(Chr(32))
Next i
FileWriter.Close()
End Sub
And to read and write the contents of the text file and write to a multi-line text box (you just need to set the multiple lines property of a text box to true) I used the following code. I also had to do some extra coding to break the individual words from the long string I received from the text file.
Private Sub cmdReadFromTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdReadFromTextfile.Click
Dim sStringFromFile As String = ""
Dim sTextString As String = ""
Dim iWordStartingPossition As Integer = 0
Dim iWordEndingPossition As Integer = 0
Dim iClearedTestLength As Integer = 0
Dim FileReader As StreamReader
FileReader = New StreamReader(FileName)
sStringFromFile = FileReader.ReadToEnd()
sTextString = sStringFromFile
txtTextFromFile.Text = ""
Do Until iClearedTestLength = Len(sTextString)
iWordEndingPossition = CInt(InStr((Microsoft.VisualBasic.Right(sTextString, Len(sTextString) - iWordStartingPossition)), " "))
txtTextFromFile.Text = txtTextFromFile.Text & (Microsoft.VisualBasic.Mid(sTextString, iWordStartingPossition + 1, iWordEndingPossition)) & vbCrLf
iWordStartingPossition = iWordStartingPossition + iWordEndingPossition
iClearedTestLength = iClearedTestLength + iWordEndingPossition
Loop
FileReader.Close()
End Sub