add instance of class to listbox from .txt visual basic - vb.net

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

Related

The row is overwriting and not adding rows listview

Im sending the data from form1(Home) to form2 (StatusReport) but the information taken from form 1 is not adding to the next row in the form2, instead it is overwriting the same row. I did it on the form 1, the adding per row but from sending the data from form 1 to form 2, it's not adding properly.
Form 1 code
Dim recipientName As String = TextBox5.Text
Dim address As String = TextBox6.Text
Dim contactNumber As String = TextBox7.Text
Dim deliveryMode As String = ComboBox3.SelectedItem
Dim deliveryDate As Date = DateTimePicker1.Value.Date
Form 2 code
Dim recipientName As String = Home.TextBox5.Text
Dim address As String = Home.TextBox6.Text
Dim contactNumber As String = Home.TextBox7.Text
Dim deliveryMode As String = Home.ComboBox3.SelectedItem
Dim deliveryDate As Date = Home.DateTimePicker1.Value.Date
Dim orderStatus As String = "Pending"
Dim str(6) As String
Dim lvItem As ListViewItem
str(0) = recipientName
str(1) = address
str(2) = contactNumber
str(3) = deliveryMode
str(4) = deliveryDate
str(5) = orderStatus
lvItem = New ListViewItem(str)
ListView1.Items.Add(lvItem)
Creating a new ListViewItem using a String Array creates a single ListViewItem with the array signifying the sub items.
Maybe simpler to create the ListViewItems individually and add them, like this:
lv.Items.Add(New ListViewItem(recipientName))
lv.Items.Add(New ListViewItem(Address))
lv.Items.Add(New ListViewItem(contactNumber))
lv.Items.Add(New ListViewItem(deliveryMode))
lv.Items.Add(New ListViewItem(recipientName))
etc.
You may want to clear the items first:
lv.Items.Clear()
It is unclear how you are going back and forth between the 2 forms but this should get you started. Set up the columns in the ListView before adding any items. You can either do this once in code or at design time. ListViews hold ListViewItems. The first column is the Text property and the following columns are SubItems.
Private Sub CreateLVColumns()
'you will probably want to do this at design time
With ListView1.Columns
.Add("Name")
.Add("Address")
.Add("Number")
.Add("Mode")
.Add("Date")
.Add("Status")
End With
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lvi As New ListViewItem(Home.TextBox5.Text)
With lvi.SubItems
.Add(Home.TextBox6.Text)
.Add(Home.TextBox7.Text)
.Add(Home.ComboBox3.Text)
.Add(Home.DateTimePicker1.Value.Date.ToString) 'you can add a format to the ToString
.Add("Pending")
End With
ListView1.Items.Add(lvi)
End Sub
found the answer, this is just the base. Just added some codes to fit into the required system.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim itm As New ListViewItem(TextBox1.Text)
itm.SubItems.Add(TextBox2.Text)
itm.SubItems.Add(TextBox3.Text)
Form2.ListView1.Items.Add(itm)
Form2.Show()
Me.Hide()
End Sub
End Class
Public Class Form2
Private Sub ListView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListView1.SelectedIndexChanged
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Form1.Show()
End Sub
End Class
Leaving this here as it can help others too.

LINQ Query Null Error

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

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

For Each Item in ListBox1 do something then add item to listbox2 vb

I made an app to convert certain numbers to other format
i.e
1 = A
2 = B
3 = C
4 = D
5 = E
ETC
I have made that function with no problem and I have been using it for quite sometime, but now I would like to do things faster and in a batch.
So it's really difficult for me to copy from a text file to my Textbox1 then press button1 then copy textbox2 to other text file.
So I was thinking in loading the text file into a List Box then do a loop for each item in that list into a second list that I can export to another text file.
The importing and exporting I have it covered but where I'm stuck at is to make the loop.
Here's what I have please if you know a better way to do it let me know or tell me how to fix it this way.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using FD As New OpenFileDialog()
FD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
If FD.ShowDialog = Windows.Forms.DialogResult.OK Then
ListBox1.Items.Clear()
ListBox1.Items.AddRange(IO.File.ReadAllLines(FD.FileName))
End If
End Using
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Do
Dim Item As String = ""
For Each i As String In ListBox1.Items
Item &= i
TextBox1.Text = Item
TextBox2.Text = MYFUNCTION(TextBox1.Text)
ListBox2.Items.Add(TextBox2.Text)
TextBox1.Text = ""
TextBox2.Text = ""
Next
Loop Until TextBox1.Text = "END"
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
'TextBox2.Text = MeidHexToDec(TextBox1.Text)
Using FD As New SaveFileDialog()
FD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
If FD.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim FileContent As String = ""
For Each i As String In ListBox2.Items
FileContent &= i & vbCrLf
Next
IO.File.WriteAllText(FD.FileName, FileContent)
End If
End Using
End Sub
So my final aim is to do something like this:
TextFile1.txt
1
2
5
5
1
3
2
END
then after the conversion output
TextFile2.txt
A
B
E
E
A
C
B
The text file size will vary sometimes it will have only 10 items sometimes will be 50...
Thanks.
You do not need the Do loop at all and you can simplify the rest of your loop logic, like this:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For Each i As String In ListBox1.Items
ListBox2.Items.Add(MYFUNCTION(i))
Next
End Sub
You do not need to look out for the END marker, because everything in the file was read into the ListBox1.Items collection, thus once you have looped through all of the string values in ListBox1.Items, then you are at the end of the file.
The MYFUNCTION logic returns the transformation from number to letter, thus just add the result of that function into ListBox2.Items and you are done.
Public Function Letr(N As Int16) As String
Letr = Chr(N + 64)
End Function

Pass variable to new form with Datatable and Listbox

I am currently trying to write an application like address book. Listbox works properly, it shows everything corretly. But I need to pass id of chosen listbox item to another form. I got code like this in Form2:
Private myTable As New DataTable()
Public Sub LoadXml(sender As Object, e As EventArgs) Handles Me.Load
With myTable.Columns
.Add("DisplayValue", GetType(String))
.Add("HiddenValue", GetType(Integer))
End With
myTable.DefaultView.Sort = "DisplayValue ASC"
ListBox1.DisplayMember = "DisplayValue"
ListBox1.ValueMember = "HiddenValue"
ListBox1.DataSource = myTable
Dim doc As New Xml.XmlDocument
doc.Load("c:\address.xml")
Dim xmlName As Xml.XmlNodeList = doc.GetElementsByTagName("name")
Dim xmlSurname As Xml.XmlNodeList = doc.GetElementsByTagName("surname")
Dim xmlId As Xml.XmlNodeList = doc.GetElementsByTagName("id")
For i As Integer = 0 To xmlName.Count - 1
Dim nazwa As String = xmlName(i).FirstChild.Value + " " + xmlSurname(i).FirstChild.Value
myTable.Rows.Add(nazwa, xmlId(i).FirstChild.Value)
MsgBox(myTable.Rows(i).Item(1).ToString)
Next i
ListBox1.Sorted = True
End Sub
Later in the code I have event:
Public Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
End Sub
I would like to know how can I call id from DataTable for selected listbox item. I hope u understand what I mean since my english is not perfect :)
Since you have added the XML value id to the data table column HiddenValue and you have assigned HiddenValue as the ValueMember for the listbox, once a record is selected in the listbox, id will be available in the listbox's [SelectedValue][1] member. For example:
Public Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
MsgBox("Selected Id: " & ListBox1.SelectedValue.ToString())
End Sub