Looking for a way to populate listview from String array - vb.net

I have a problem populating a ListView with an I have created. All of the data goes to one column instead of rows. Could you help me to populate it correctly?
Dim finalas() As String = arrf.ToArray(GetType(System.String))
For Each element As String In finalas
Dim item As New ListViewItem(element)
ListView1.Items.Add(item)
Next

I have found a solution myself, if some one needs it, here you go:
Sub readTextFile()
' Create new StreamReader instance with Using block.
Dim path As String = "D:\data.txt"
Dim st() As String = File.ReadAllLines(path) 'read the file into array of
Dim p_1 As String = ""
Dim p_2 As String = ""
Dim arrl As Integer = 11
For Each itm As String In st 'loop the array of string item by item
Dim Arr() As String = itm.Split(New String() {" "}, StringSplitOptions.RemoveEmptyEntries) 'split the string
Dim name() As String = itm.Split(New String() {"'"}, StringSplitOptions.RemoveEmptyEntries)
' Arr.Skip(1).ToArray -nenuskaito pirmojo
' Arr = Arr.Take(Arr.Length - 1).ToArray - nenuskaito paskutinio
'galutinis array
p_1 = Arr(1)
p_2 = Arr(2)
Dim finarr As New List(Of String)
finarr.Add(p_1)
finarr.Add(p_2)
finarr.Add(name(1))
For i As Integer = 4 To arrl
finarr.Add(Arr(((Arr.Length - 1) - arrl) + i))
Next
'MsgBox(finarr(0) & finarr(1) & finarr(2) & finarr(3) & finarr(4) & finarr(5) & finarr(6) & finarr(7) & finarr(8) & finarr(9) & finarr(10))
Dim items As New List(Of ListViewItem)
Dim lvItem = New ListViewItem(finarr(0))
For i = 1 To 10
lvItem.SubItems.Add(finarr(i))
Next i
items.Add(lvItem)
ListView1.Items.AddRange(items.ToArray)
Next
Return
End Sub

Related

Receive object reference error when iterate the xdocument to retrieve xml element value

Dim lstrReadXml As String = String.Empty
mobjComFun.ReadTextFile(System.Windows.Forms.Application.StartupPath & "\GoFirstBookingXML\GetBookRes.xml", lstrReadXml)
Dim lobjXdoc As XDocument = XDocument.Parse(lstrReadXml)
Dim lobjNs As New XmlNamespaceManager(lobjXdoc.CreateReader.NameTable)
lobjNs.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/")
lobjNs.AddNamespace("sc", "http://schemas.navitaire.com/WebServices/ServiceContracts/BookingService")
lobjNs.AddNamespace("dc", "http://schemas.navitaire.com/WebServices/DataContracts/Booking")
lobjNs.AddNamespace("a", "http://schemas.navitaire.com/WebServices/DataContracts/Common")
Dim lstrErrorMsg = String.Empty, lstrQueryStr As String = String.Empty
Dim lstrPaxNames As New StringBuilder
'Dim lstrFirstName As String = mobjComFun.GetElementValue(lobjXdoc, "/s:Envelope/s:Body/sc:GetBookingResponse/dc:Booking/dc:Passengers/dc:Passenger/dc:Names", lobjNs, lstrErrorMsg)
For Each lobXnode In lobjXdoc.XPathSelectElements("/s:Envelope/s:Body/sc:GetBookingResponse/dc:Booking/dc:Passengers/dc:Passenger", lobjNs)
If Not lobXnode Is Nothing Then
Dim lobjIEnum As IEnumerable(Of XElement) = From Nam In lobXnode.Elements(lobjNs. & "Names")
Select Nam
Dim lstrLN As String = lobXnode.Document.Element("LastName").Value
lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names", lobjNs).Value)
lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names/dc:BookingName/dc:LastName", lobjNs).Value & "/")
lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names/dc:BookingName/dc:FirstName", lobjNs).Value & " Y58TWL ")
End If
Next
When trying to foreach iterate the XDocument, I receive the object reference error when trying to get the element value inside the iteration.

Drag and drop multiple files by filter into listview

I'm currently have this code to store data to listview
I have to store first the info to textbox lines and then store them to listview.
Is there easy way without storing first textbox and directly put the files into listview?
What I want is to drag and drop or browse the multiple video ts file in the first column and then the srt in the sub column.
hope that you know what I mean. I'm rally new in listview
Sub AddToListView()
LV.Items.Clear()
Dim vn = vName.Lines
Dim sn = sName.Lines
Dim vp = vPath.Lines
Dim sp = sPath.Lines
Dim items As New List(Of ListViewItem)
Dim upper = {vn.GetUpperBound(0), sn.GetUpperBound(0), vp.GetUpperBound(0), sp.GetUpperBound(0)}
For I = 0 To upper.Min
items.Add(New ListViewItem({vn(I), sn(I), vp(I), sp(I)}))
Next
LV.BeginUpdate()
LV.Items.AddRange(items.ToArray())
SortItems()
LV.EndUpdate()
AddToParam()
End Sub
Sub readFiles()
Dim folder As String = txtinputFolder.Text
Dim sb1 As New StringBuilder
Dim sb2 As New StringBuilder
Dim sb3 As New StringBuilder
Dim sb4 As New StringBuilder
For Each item In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
sb1.Append(item & vbNewLine)
Next
vPath.Text = ""
vPath.Text = sb1.ToString.Trim
For Each file As String In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
sb2.Append(Path.GetFileName(file) & vbNewLine)
Next
vName.Text = ""
vName.Text = sb2.ToString.Trim
For Each file As String In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.srt")
sb3.Append(Path.GetFileName(file) & vbNewLine)
Next
sName.Text = ""
sName.Text = sb3.ToString.Trim
For Each item3 In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.srt")
sb4.Append(item3 & vbNewLine)
Next
sPath.Text = ""
sPath.Text = sb4.ToString.Trim
End Sub
If i'm not wrong subtitle name should be the same as the movie
Sub readFiles(ByVal searchdirectory As String)
For Each FullPath In My.Computer.FileSystem.GetFiles(searchdirectory, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
Dim parentPath As String = Path.GetDirectoryName(FullPath)
Dim movieName As String = Path.GetFileNameWithoutExtension(FullPath)
Dim srtPath As String = parentPath & "\" & movieName & ".srt"
If File.Exists(srtPath) Then
Lv.Items.Add(FullPath).SubItems.AddRange(New String() {movieName & ".ts", srtPath, movieName & ".srt"})
Else
Lv.Items.Add(FullPath).SubItems.AddRange(New String() {movieName & ".ts", "Not Exist", "No subtitle"})
End If
Next
Lv.Sorting = SortOrder.Ascending
Lv.Sort()
End Sub
usage
readFiles("you path")
You could try something like this:
Sub AddToListView(vNames As String(), sNames As String(), vPaths As String(), sPaths As String())
LV.Items.Clear()
Dim items As New List(Of ListViewItem)
Dim upperBounds = {vNames.GetUpperBound(0), sNames.GetUpperBound(0), vPaths.GetUpperBound(0), sPaths.GetUpperBound(0)}
For i = 0 To upperBounds.Min
items.Add(New ListViewItem({vNames(i), sNames(i), vPaths(i), sPaths(i)}))
Next
LV.BeginUpdate()
LV.Items.AddRange(items.ToArray())
SortItems()
LV.EndUpdate()
AddToParam()
End Sub
Sub readFiles()
Dim folder As String = txtinputFolder.Text
Dim vPaths As New List(Of String)
Dim vNames As New List(Of String)
Dim sPaths As New List(Of String)
Dim sNames As New List(Of String)
For Each filePath In Directory.EnumerateFiles(folder, "*.ts")
vPaths.Add(filePath)
vNames.Add(Path.GetFileName(filePath))
Next
For Each filePath In Directory.EnumerateFiles(folder, "*.srt")
sPaths.Add(filePath)
sNames.Add(Path.GetFileName(filePath))
Next
AddToListView(vNames.ToArray(), sNames.ToArray(), vPaths.ToArray(), sPaths.ToArray())
End Sub
If you don't want readFiles calling AddToListView, you could use fields to store the data rather than local variables, or you could have readFields return the data in a Tuple or some dedicated object.
This seems like a reasonable answer based on the code provided and the actual question asked but it has nothing to do with drag and drop, so I'm not sure whether I'm missing something or you are.
Thank you here's my updated code:
since I want to show first the filename I tried to re-edit the code.
Sub readFiles(ByVal searchdirectory As String)
For Each FullPath In My.Computer.FileSystem.GetFiles(searchdirectory, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
Dim parentPath As String = Path.GetDirectoryName(FullPath)
Dim movieName As String = Path.GetFileNameWithoutExtension(FullPath)
Dim srtPath As String = parentPath & "\" & movieName & ".srt"
Dim allPath As String = parentPath & "\" & movieName
If File.Exists(srtPath) Then
LV.BeginUpdate()
Dim lvi As New ListViewItem
With lvi
.Text = movieName & ".ts" 'video filename
.SubItems.Add(movieName & ".srt") 'subtitle filename
.SubItems.Add(movieName & ".mkv") 'output filename
.SubItems.Add(allPath & ".ts") 'video path
.SubItems.Add(allPath & ".srt") 'subtitle path
End With
LV.Items.Add(lvi)
LV.EndUpdate()
Else
MsgBox("srt file not found in the folder", vbInformation, "")
End If
Next
LV.Sorting = SortOrder.Ascending
LV.Sort()
End Sub

Variable '' is used before it has been assigned a value.

I'm trying to make a program that downloads a bunch of domains and adds them windows hosts file but I'm having a bit of trouble. I keep getting an error when I try storing them in a list. I don't get why it doesn't work.
Sub Main()
Console.Title = "NoTrack blocklist to Windows Hosts File Converter"
Console.WriteLine("Downloading . . . ")
Dim FileDelete As String = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "/Downloads" & "/notracktemp.txt"
If System.IO.File.Exists(FileDelete) = True Then
System.IO.File.Delete(FileDelete)
End If
download()
Threading.Thread.Sleep(1000)
Dim s As New IO.StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "/Downloads" & "/notracktemp.txt", True)
Dim tempRead As String ' = s.ReadLine
Dim tempSplit As String() ' = tempRead.Split(New Char() {" "})
Dim i As Integer = 0
Dim tempStore As String()
s.ReadLine()
s.ReadLine()
Do Until s.EndOfStream = True
tempRead = s.ReadLine
tempSplit = tempRead.Split(New Char() {" "})
Console.WriteLine(tempSplit(0))
tempStore(i) = tempSplit(0)'The part that gives me the error
i = i + 1
Loop
Console.ReadKey()
End Sub
Sub download()
Dim localDir As String = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
'"Enter file URL"
Dim url As String = "https://quidsup.net/notrack/blocklist.php?download"
'"Enter directory"
Dim dirr As String = localDir & "/Downloads" & "/notracktemp.txt"
My.Computer.Network.DownloadFile(url, dirr)
'System.IO.File.Delete(localDir & "/notracktemp.txt")
End Sub
tempStore() has to have a size
count number of lines in file with loop, then declare it as tempStore(i) where i is the amount of lines. Here is a function that counts the lines.
Function countlines()
Dim count As Integer
Dim s As New IO.StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "/Downloads" & "/notracktemp.txt", True)
s.ReadLine()
s.ReadLine()
count = 0
Do Until s.EndOfStream = True
s.ReadLine()
count = count + 1
Loop
Console.WriteLine(count)
Return count
Console.ReadKey()
End Function
Then what you do is:
Dim count As Integer
count = countlines()
Dim tempStore(count) As String

vb.net how do i add long text into csv

hello this is my firs thread ,
i'm trying to convert description of this page (https://www.tokopedia.com/indoislamicstore/cream-zaitun-arofah)
with regex and replace <br/> tag with new line and convert it to csv .
the datagridview it's alright but the csv got screwed
this is my code :
Dim dskrip As New System.Text.RegularExpressions.Regex("<p itemprop=""description"" class=""mt-20"">(.*?)\<\/p>\<\/div>")
Dim dskripm As MatchCollection = dskrip.Matches(rssourcecode0)
For Each itemdskrm As Match In dskripm
getdeskripsinew = itemdskrm.Groups(1).Value
Next
Dim deskripsinew As String = Replace(getdeskripsinew, ",", ";")
Dim deskripsitotal As String = Replace(deskripsinew, "<br/>", Environment.NewLine)
' ListView1.s = Environment.NewLine & deskripsinew
txtDeskripsi.Text = deskripsitotal
datascrapes.ColumnCount = 5
datascrapes.Columns(0).Name = "Title"
datascrapes.Columns(1).Name = "Price"
datascrapes.Columns(2).Name = "Deskripsi"
datascrapes.Columns(3).Name = "Gambar"
datascrapes.Columns(4).Name = "Total Produk"
Dim row As String() = New String() {getname, totalprice, deskripsitotal, directoryme + getfilename, "10"}
datascrapes.Rows.Add(row)
Dim filePath As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\" & "Tokopedia_Upload.csv"
Dim delimeter As String = ","
Dim sb As New StringBuilder
For i As Integer = 0 To datascrapes.Rows.Count - 1
Dim array As String() = New String(datascrapes.Columns.Count - 1) {}
If i.Equals(0) Then
For j As Integer = 0 To datascrapes.Columns.Count - 1
array(j) = datascrapes.Columns(j).HeaderText
Next
sb.AppendLine(String.Join(delimeter, array))
End If
For j As Integer = 0 To datascrapes.Columns.Count - 1
If Not datascrapes.Rows(i).IsNewRow Then
array(j) = datascrapes(j, i).Value.ToString
End If
Next
If Not datascrapes.Rows(i).IsNewRow Then
sb.AppendLine(String.Join(delimeter, array))
End If
Next
File.WriteAllText(filePath, sb.ToString)
this is the csv file
I'm not sure where your problem is looking at the CSV file, but there are certain cases where you'll want to quote the values for a CSV. There's no official spec but RFC 4180 is often used as an unofficial standard. I would recommend using a library like CSV Helper

Stored list of array using For Each loop

I want to store the "zone_check_value" to a array of string then while inserting into array i will check the array of string if the next value is repeated or have duplicate.
Example.
1st Example
1st loop = zone_check_value = ZD1/01/2014
2nd loop = zone_check_value = ZD1/01/2014
2nd Example
1st loop = zone_check_value = ZD1/01/2014
2nd loop = zone_check_value = ZD2/02/2014
3rd loop = zone_check_value = ZD1/01/2014
Code:
For Each dt As DataTable In xls.Tables
Dim array_of_string as String() 'i want to put the value in here
For Each dr As DataRow In dt.Rows
Dim zone_destination As String = dr(2).ToString
Dim affected_date As String = dr(7).ToString
Dim zone_check_value = zone_destination + affected_date
''''''How can i store zone_check_value in a string array?
Next
Next
EDIT
What if i add select case in my loop? the array_of_string value become NULL. I need to check the value of the current value in array_of_string .
Example Code
For Each dt As DataTable In xls.Tables
Dim array_of_string as String() 'i want to put the value in here
select Case dt.tablename
case "Sheet1"
For Each dr As DataRow In dt.Rows
Dim zone_destination As String = dr(2).ToString
Dim affected_date As String = dr(7).ToString
Dim zone_check_value = zone_destination + affected_date
''''''How can i store zone_check_value in a string array?
Next
case "Sheet 2"
For Each dr As DataRow In dt.Rows
Dim check_value as Boolean = array_of_string.Contains(dr(0).ToString)
'but when i got in sheet 2 the array_of_string is null
Next
Next
The easiest way is to use a List(Of String).
For Each dt As DataTable In xls.Tables
Dim array_of_string as List(Of String) = New List(Of String) 'i want to put the value in here
For Each dr As DataRow In dt.Rows
Dim zone_destination As String = dr(2).ToString
Dim affected_date As String = dr(7).ToString
Dim zone_check_value = zone_destination & affected_date
''''''How can i store zone_check_value in a string array?
array_of_string.Add(zone_check_value)
Next
''' Now if you really need it in array form you can cast it via:
''' Dim values() As String = array_of_string.ToArray()
Next
You might even consider:
For Each dt As DataTable In xls.Tables
Dim values As List(Of String) = New List(Of String)
dt.Rows.ForEach( Sub(item) values.Add(item(2).ToString & item(7).ToString) )
''' Now do something with values.
Next
Either way, make sure you always use the string concatenation operator & to concatenate strings. The arithmetic addition operator + will cause you problems from time to time if you use it on strings.