LINQ Query Null Error - vb.net

I have am making an email contact search, where I am supposed to open a text file using the OpenFileDialog, and then split it to an array and search using LINQ. I have the openFileDialog working, but when I run my LINQ query, I get the object reference not set to an instance of an object error. Option Infer is on, and as far as I can tell this is set up exactly like some of the examples in my textbook. Can anyone point me in the right direction??? (textFile is defined as a class variable above the first button code: "Dim textFile(2) As String".
Code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles BtnOpen.Click
OpenFileDialog1.ShowDialog()
textFile(2) = OpenFileDialog1.FileName
lstOutput.DataSource = IO.File.ReadAllLines(textFile(2))
lstOutput.SelectedItem = Nothing
End Sub
Private Sub btnNameSearch_Click(sender As Object, e As EventArgs) Handles btnNameSearch.Click
Dim queryName = From line In textFile
Let data = line.Split(","c)
Let firstName = data(0)
Let lastName = data(1)
Let email = data(2)
Where firstName = txtName.Text
Select firstName, lastName, email
lstName.DataSource = queryName.ToList
End Sub
Edit: Code breaks on line 21 "Let data=line.Split(","c)

You're using the filename as the string that LINQ is querying against. You need to use the file contents itself.
Change your code to something like this:
Private lines() As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles BtnOpen.Click
If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
textFile(2) = OpenFileDialog1.FileName
lines = IO.File.ReadAllLines(textFile(2))
lstOutput.DataSource = lines
lstOutput.SelectedItem = Nothing
End If
End Sub
Private Sub btnNameSearch_Click(sender As Object, e As EventArgs) Handles btnNameSearch.Click
Dim queryName = From line In lines
Let data = line.Split(","c)
Let firstName = data(0)
Let lastName = data(1)
Let email = data(2)
Where firstName = txtName.Text
Select firstName, lastName, email
lstName.DataSource = queryName.ToList
End Sub

Related

How to remove path in my search code on vb.net

I am very new to VB and I have an assignment which requires me to have search code in the program.The search code works but it shows the path of the file and I just want it to show the name of the txt file.
Private Sub SearchOrdersToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SearchOrdersToolStripMenuItem.Click
txtSearch.Visible = True
Lblsearch.Visible = True
Dim backslash As String() = FrmLogIn.FolderDirectory.Split("\")
Dim filename As String = backslash(6)
ListOfAllFileNames = System.IO.Directory.GetFiles(FrmLogIn.FolderDirectory)
TxtShoworders.Lines = ListOfAllFileNames
End Sub
Private Sub txtSearch_TextChanged(sender As Object, e As EventArgs) Handles txtSearch.TextChanged
If txtSearch.Text = "" Then
TxtShoworders.Lines = ListOfAllFileNames
Return
Else
Dim SearchResults As New List(Of String)
For Each currentFileName In ListOfAllFileNames
If currentFileName.Contains(txtSearch.Text) Then
SearchResults.Add(currentFileName)
End If
Next
TxtShoworders.Lines = SearchResults.ToArray()
End If
End Sub
Link to what the program looks like and the directory showing
If anyone could help me with this that would be great, thanks.
You'll have to use Path.GetFileName for this, example:
SearchResults.Add(Path.GetFileName(currentFileName))
To keep your list of paths but only show the filenames, try this:
Private Sub SearchOrdersToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SearchOrdersToolStripMenuItem.Click
txtSearch.Visible = True
Lblsearch.Visible = True
Dim backslash As String() = FrmLogIn.FolderDirectory.Split("\")
Dim filename As String = backslash(6)
ListOfAllFileNames = System.IO.Directory.GetFiles(FrmLogIn.FolderDirectory)
TxtShoworders.Lines = GetFileNames(ListOfAllFileNames)
End Sub
Private Sub txtSearch_TextChanged(sender As Object, e As EventArgs) Handles txtSearch.TextChanged
If txtSearch.Text = "" Then
TxtShoworders.Lines = GetFileNames(ListOfAllFileNames)
Return
Else
Dim SearchResults As New List(Of String)
For Each currentFileName In ListOfAllFileNames
If currentFileName.Contains(txtSearch.Text) Then
SearchResults.Add(currentFileName)
End If
Next
TxtShoworders.Lines = GetFileNames(SearchResults.ToArray())
End If
End Sub
Private Function GetFileNames(Byval paths as String()) As String()
Return paths.Select(Function(p) Path.GetFileName(p)).ToArray()
End Function
This will keep your ListOfAllFileNames containing the paths while only showing the file names using GetFileNames.

How can I display a name in a different sequence using strings?

I'm having trouble with a problem that I was assigned for my Visual Basic 2012 class. The instructions are below. So far, I have it displaying only the first name entered, and nothing else. How can I make it to display both the first name and the last name in the sequence requested?
String Problem: Enter your first and last name in a text box. Take the name and display it in a label box showing the last name, first name.
Text Box Entry: Jane Doe
Label Box: Doe, Jane
The code I have so far is below. Thanks for any help!
Private Sub btndisplay_Click(sender As Object, e As EventArgs) Handles btndisplay.Click
Dim fullname As String
Dim firstname As String
Dim indexnum As Integer
Dim lastname As String
fullname = fulltextbox.Text
indexnum = fullname.IndexOf(" ")
firstname = fullname.Substring(0, indexnum)
firstlabel.Text = firstname
fulltextbox.Focus()
End Sub
Private Sub fulltextbox_TextChanged(sender As Object, e As EventArgs)
firstlabel.Text = String.Empty
fulltextbox.SelectAll()
End Sub
Private Sub btnexit_Click(sender As Object, e As EventArgs) Handles btnexit.Click
Me.Close()
End Sub
You are on the right track by first determining where the space is located:
indexnum = fullname.IndexOf(" ")
Now based on this index, you can split the string into two strings, firstname and lastname:
firstname = fullname.Substring(0, indexnum)
lastname = fullname.Substring(indexnum+1)
You need to use indexnum+1, instead of indexnum, otherwise you will include the spacing character.
Finally you group them together again by using the string concatenation operator (&):
firstlabel.Text = lastname & ", " & firstname
The final method thus looks like:
Private Sub btndisplay_Click(sender As Object, e As EventArgs) Handles btndisplay.Click
Dim fullname As String
Dim firstname As String
Dim indexnum As Integer
Dim lastname As String
fullname = fulltextbox.Text
indexnum = fullname.IndexOf(" ")
firstname = fullname.Substring(0, indexnum)
lastname = fullname.Substring(indexnum+1)
firstlabel.Text = lastname & ", " & firstname
fulltextbox.Focus()
End Sub
Note, this won't work if your using middle initials. Also, I would remove fulltextbox.SelectAll() from fulltextbox_TextChanged
Private Sub btndisplay_Click(sender As Object, e As EventArgs) Handles btndisplay.Click
Dim Names() As String = fulltextbox.Text.Split(" "c)
If Names.Count = 2 Then
firstlabel.Text = Names(1) + ", " + Names(0)
ElseIf Names.Count = 0 Then
MessageBox.Show("Please enter name.")
Else
MessageBox.Show("Invalid Nmae entered.")
End If
fulltextbox.Text = ""
End Sub

transfering fixed words in multiline textbox in visual basic to seperate single line textboxes

I am having problem in visual basic textbox so my actual problem is i have a Multiline textbox1 containing FirstName="JOHN" in one line and LastName="SMITH" in the newline and i want to transfer only JOHN in separate singleline textbox2 and SMITH in other singleline textbox3.
i want this to happen on click of copy button.
The lefthanside of the textbox1 like FirstName,LastName remains constant whereas the rightside like JOHN,SMITH are changing in nature.
I have created a separate function and i have tried so far as
Public Class Form1
Dim itemsInTextBox As String() = TextBox1.Text.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
Dim firstName As String = itemsInTextBox(0).Split("=".ToCharArray)(1)
Dim secondName As String = itemsInTextBox(1).Split("=".ToCharArray)(1)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox2.Text = firstName
TextBox3.Text = secondName
End Sub
End Class
here's the link to screenshot of what i want to accomplish.
http://tinypic.com/r/2mcev5w/8
Thanks in advance
I think you could separate the text from the textbox by new lines. Something like:
Dim itemsInTextBox as String() = TextBox1.Text.Split(vbCrLf.toCharArray, StringSplitOptions.RemoveEmptyEntries)
Dim firstName as String = itemsInTextBox(0).Split("=".toCharArray)(1)
Dim secondName as String = itemsInTextBox(1).Split("=".toCharArray)(1)
This is assuming your lines in the textbox are separated by new lines. If it is separated by something else, just put that in the split method. This also keeps the quotation marks (do you want this?)
EDIT: for setting other textboxes
TextBox2.Text = firstName
TextBox3.Text = secondName
EDIT2: You have to create those variables on button click. If you do it globally, it will be run before your TextBox1 exists.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim itemsInTextBox As String() = TextBox1.Text.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
Dim firstName As String = itemsInTextBox(0).Split("=".ToCharArray)(1)
Dim secondName As String = itemsInTextBox(1).Split("=".ToCharArray)(1)
TextBox2.Text = firstName
TextBox3.Text = secondName
End Sub
Your sample and your description are different. In your sample you use FIRSTNAME=JOHN and in your description you use first-name="john" which are very different.
Lets use your sample. Your test should look like this.
TextBox2.Text = GetValue("FIRSTNAME=JOHN" & vbcrlf & "LASTNAME=SMITH")
TextBox3.Text = GetValue("FIRSTNAME=JOHN" & vbcrlf & "LASTNAME=SMITH")
Of you try it like this, you will see it's not returning the right information.
You'll have to split each line and then split these line again with the = sign like you did.
Function GetValue(ByVal data As String, ByVal key As String) As String
Dim lines() As String = data.Split(Chr(10))
For Each line As String In lines
line = line.Trim()
Dim subData() As String = line.Split("="c)
If subData(0) = key Then
Return subData(1)
End If
Next
Return ""
End Function
Sub Main()
Dim data As String
data = "FIRSTNAME=JOHN" & Environment.NewLine & "LASTNAME=SMITH"
Console.WriteLine(GetValue(data, "FIRSTNAME"))
Console.WriteLine(GetValue(data, "LASTNAME"))
Console.ReadLine()
End Sub
Just move the declaration of the itemsList into the sub for the copy.
EDIT: Also need to move the declaration of the strings
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim itemsInTextBox As String() = TextBox1.Text.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
Dim firstName As String = itemsInTextBox(0).Split("=".ToCharArray)(1)
Dim secondName As String = itemsInTextBox(1).Split("=".ToCharArray)(1)
TextBox2.Text = firstName
TextBox3.Text = secondName
End Sub

Why does my function write to file not write to file when combined with a combobox

I have narrowed it down to that i believe it is my write to file function. when i run the program and add an instance it does not even write anything to the designated file.
i am trying to figure out how to select an item from the combobox and then have the following textbox next to it add its information into the correct place in the file.
here is the code i have so far:
Option Strict On
Public Class frmSemseter_Project_ll
Dim ComicArray() As String = IO.File.ReadAllLines("Comics.txt")
Private Sub frmSemseter_Project_ll_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dgvComics.DataSource = ComicArray.ToList
DisplayComicData(dgvComics, "Comics.txt")
End Sub
Private Sub mnuFile_Exit_Click(sender As Object, e As EventArgs) Handles mnuFile_Exit.Click
'Closes the program
Me.Close()
End Sub
Private Sub DisplayComicData(ByRef dgv As DataGridView, filename As String)
dgvComics.Refresh()
If IO.File.Exists(filename) Then
Dim query = From Line In IO.File.ReadAllLines(filename)
Let Title = Line.Split(","c)(0)
Let Issue = Line.Split(","c)(1)
Let Publisher = Line.Split(","c)(2)
Let CoverDate = Line.Split(","c)(3)
Let CoverPrice = FormatCurrency(Line.Split(","c)(4))
Let AddedDate = Line.Split(","c)(5)
Order By Title Ascending
Select Title, Issue, Publisher, CoverDate, CoverPrice, AddedDate
dgvComics.DataSource = query.ToList()
ElseIf Not IO.File.Exists("Comics.txt") Then
MessageBox.Show("ERROR: Please Insert the Comics File.", "No File",
MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Sub
Private Sub mnuSort_Ascending_Title_Click(sender As Object, e As EventArgs) Handles mnuSort_Ascending_Title.Click
Dim query = From Line In ComicArray
Let Title = Line.Split(","c)(0)
Let Issue = Line.Split(","c)(1)
Let Publisher = Line.Split(","c)(2)
Let CoverDate = Line.Split(","c)(3)
Let CoverPrice = FormatCurrency(Line.Split(","c)(4))
Let AddedDate = Line.Split(","c)(5)
Order By Title Ascending
Select Title, Issue, Publisher, CoverDate, CoverPrice, AddedDate
dgvComics.DataSource = query.ToList()
End Sub
Private Sub mnuSort_Desending_Title_Click(sender As Object, e As EventArgs) Handles mnuSort_Desending_Title.Click
Dim query = From Line In ComicArray
Let Title = Line.Split(","c)(0)
Let Issue = Line.Split(","c)(1)
Let Publisher = Line.Split(","c)(2)
Let CoverDate = Line.Split(","c)(3)
Let CoverPrice = FormatCurrency(Line.Split(","c)(4))
Let AddedDate = Line.Split(","c)(5)
Order By Title Descending
Select Title, Issue, Publisher, CoverDate, CoverPrice, AddedDate
dgvComics.DataSource = query.ToList()
End Sub
Private Sub mnuSort_Ascending_Issue_Click(sender As Object, e As EventArgs) Handles mnuSort_Ascending_Issue.Click
Dim query = From Line In ComicArray
Let Title = Line.Split(","c)(0)
Let Issue = Line.Split(","c)(1)
Let Publisher = Line.Split(","c)(2)
Let CoverDate = Line.Split(","c)(3)
Let CoverPrice = FormatCurrency(Line.Split(","c)(4))
Let AddedDate = Line.Split(","c)(5)
Order By Issue Ascending
Select Title, Issue, Publisher, CoverDate, CoverPrice, AddedDate
dgvComics.DataSource = query.ToList()
End Sub
Private Sub mnuSort_Desending_Issue_Click(sender As Object, e As EventArgs) Handles mnuSort_Desending_Issue.Click
Dim query = From Line In ComicArray
Let Title = Line.Split(","c)(0)
Let Issue = Line.Split(","c)(1)
Let Publisher = Line.Split(","c)(2)
Let CoverDate = Line.Split(","c)(3)
Let CoverPrice = FormatCurrency(Line.Split(","c)(4))
Let AddedDate = Line.Split(","c)(5)
Order By Issue Descending
Select Title, Issue, Publisher, CoverDate, CoverPrice, AddedDate
dgvComics.DataSource = query.ToList()
End Sub
'Everything works fine until this point
'from here through the whole write to file function does not seem to be working
'whenever i click the add button that i made it does not even add the values into the file
Private Sub btnAddComic_Click(sender As Object, e As EventArgs) Handles btnAddComic.Click
If cbComicAdder.SelectedText = "Title" Then
WriteToFile("Comics.txt", CStr(txtComicAdder.Text), "Title")
End If
If cbComicAdder.SelectedText = "Issue" Then
WriteToFile("Comics.txt", CStr(txtComicAdder.Text), "Issue")
End If
If cbComicAdder.SelectedText = "Publisher" Then
WriteToFile("Comics.txt", CStr(txtComicAdder.Text), "Publisher")
End If
If cbComicAdder.SelectedText = "Cover Date" Then
WriteToFile("Comics.txt", CStr(txtComicAdder.Text), "Cover Date")
End If
If cbComicAdder.SelectedText = "Cover Price" Then
WriteToFile("Comics.txt", CStr(txtComicAdder.Text), "Cover Price")
End If
If cbComicAdder.SelectedText = "Added Date" Then
WriteToFile("Comics.txt", CStr(txtComicAdder.Text), "Added Date")
End If
End Sub
Private Sub WriteToFile(ByVal filename As String, ByVal Item As String, ByVal Instance As String)
Dim sw As IO.StreamWriter = IO.File.AppendText(filename)
While CBool(Instance)
If Instance = "Title" Then
sw.Write(Item & ",")
ElseIf Instance = "Issue" Then
sw.Write(Item & ",")
ElseIf Instance = "Publisher" Then
sw.Write(Item & ",")
ElseIf Instance = "Cover Date" Then
sw.Write(Item & ",")
ElseIf Instance = "Cover Price" Then
sw.Write(Item & ",")
ElseIf Instance = "Added Date" Then
sw.Write(Item)
End If
End While
sw.Close()
End Sub
'how can i fix this function so that it will work?
Private Sub btnRefreshGrid_Click(sender As Object, e As EventArgs) Handles btnRefreshGrid.Click
dgvComics.ClearSelection()
dgvComics.Refresh()
dgvComics.Update()
End Sub
End Class
Example Class version
Public Class Comic
Public Property Title As String
Public Property Issue As Integer
' etc
Public Sub SaveData
Using sw As New StreamWriter(yourFileNameHere)
sr.WriteLine("{0}, {1}, {2}, ...{n}",
Title, Issue, Publisher, IssueDate, SoForth, SoOn)
End Using
End Sub
The string describes the format or layout which is mainly the , then the data to write.
If your app relies on the user to fill in and save fields one at a time, that may prove to be problematic. Before saving, the class could check to see if all the info is there to prevent partial records being written.

add instance of class to listbox from .txt visual basic

New at visual basic. I'm trying to read from a csv file, split it, then take values only at index(0) and add them all to a listbox. Here's what I got. Any advice I'd appreciate.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim data() As String
Dim initFileContents() As String = IO.File.ReadAllLines("MembershipPhone.txt")
data = initFileContents.First.Split(","c)
name = data(0)
phone = data(1)
ListBox1.Items.Add(name)
TextBox1.Text = name
TextBox2.Text = phone
End Sub
Of course this only adds the first instance. I need C++ equivalent to "for each line in data.."
Just use a For loop to iterate over the lines returned by ReadAllLines():
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim data() As String
For Each line As String In IO.File.ReadAllLines("MembershipPhone.txt")
data = line.Split(","c)
Name = data(0)
phone = data(1)
ListBox1.Items.Add(Name)
TextBox1.Text = Name
TextBox2.Text = phone
Next
End Sub