Read lines from a text file in VB.NET - vb.net

I have a text file format:
*******************************************************************************
* Mitecs Test Plan *
*******************************************************************************
[PRODUCTN]
FQA=3F.4.W0,41,1
RSC=3F.5.W4,36,1
CFG=3F.9.2J,234,1
[MASTERREV]
MTP=3F.R.WM
[FQA 13]
FQA=3F.4.W0,41,1
CFG=3F.9.2J,263,1
[FQA 14]
FQA=3F.4.W0,160,1
CFG=3F.9.2J,315,1
I want to read text and display it in the list box, something like the below:
[PRODUCTN]
[MASTERREV]
[FQA 13]
[FQA 14]
From the above image, when I the select [FQA 14] item in list box 1 and click on the swap button, it should display in the below format in listbox 2 as
Code Name Version
160 FQA 3F.4.W0
315 CFG 3F.9.2J

One option is to use a class to hold each entry and override the ToString function to return the heading. Now you can add each entry directly to listbox1 and it will show the title to represent the item. Since each listbox item actually is an object you can cast the selected item as your entry class and read the data from the object. Here's one way to do it:
Public Class Entry
Public Property Title As String = ""
Public Property Data As New List(Of String)
Public Overrides Function ToString() As String
Return Title
End Function
End Class
Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim sr As New StreamReader("textfile1.txt")
Do Until (sr.EndOfStream)
Dim line As String = sr.ReadLine.Trim
If line.StartsWith("[") Then
Dim newentry As New Entry
newentry.Title = line
Do Until (line = "" OrElse sr.EndOfStream)
line = sr.ReadLine.Trim
If Not line = "" Then
newentry.Data.Add(line)
End If
Loop
ListBox1.Items.Add(newentry)
End If
Loop
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim selectedentry As Entry = DirectCast(DirectCast(sender, ListBox).SelectedItem, Entry)
ListBox2.Items.Clear()
For Each datum In selectedentry.Data
Dim line As String() = datum.Split("=,".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
If line.Count > 2 Then
ListBox2.Items.Add(line(2) + vbTab + line(0) + vbTab + line(1))
Else
ListBox2.Items.Add(" " + vbTab + line(0) + vbTab + line(1))
End If
Next
End Sub

Related

How to make a loop for this

If NUD_Pepperoni.Value > 0 Then
txtSummary.AppendText(vbNewLine + "Pepperoni" + vbTab & vbTab & NUD_Pepperoni.Text + vbTab & price.ToString("c1") + vbTab + vbTab & (NUD_Pepperoni.Value * price).ToString("c1") + vbNewLine)
End If
If NUD_Hawaiian.Value > 0 Then
txtSummary.AppendText(vbNewLine + "Hawaiian" + vbTab & vbTab & vbTab & NUD_Hawaiian.Text + vbTab & price.ToString("c1") + vbTab + vbTab & (NUD_Hawaiian.Value * price).ToString("c1") + vbNewLine)
End If
If NUD_Americano.Value > 0 Then
txtSummary.AppendText(vbNewLine + "Americano" + vbTab & vbTab & NUD_Americano.Text + vbTab & price.ToString("c1") + vbTab + vbTab & (NUD_Americano.Value * price).ToString("c1") + vbNewLine)
End If
there are 12 of them the same
And the code below is the value I store
Dim Pizzalist(11, 1) As Single
================================================================
For p = 0 To 5
Pizzalist(p, 0) = 8.5 'store the regular pizza Price
Next
For p = 6 To 11
Pizzalist(p, 0) = 13.5 'store the gourmet pizza price
Next
================================================================
Pizzalist(0, 1) = NUD_Pepperoni.Value
Pizzalist(1, 1) = NUD_Hawaiian.Value
Pizzalist(2, 1) = NUD_Americano.Value
Pizzalist(3, 1) = NUD_TacoFiesta.Value
Pizzalist(4, 1) = NUD_Margherita.Value
Pizzalist(5, 1) = NUD_BeefOnion.Value
Pizzalist(6, 1) = NUD_BNY.Value
Pizzalist(7, 1) = NUD_MML.Value
Pizzalist(8, 1) = NUD_IL.Value
Pizzalist(9, 1) = NUD_GSS.Value
Pizzalist(10, 1) = NUD_AC.Value
Pizzalist(11, 1) = NUD_TMC.Value'store the amount of specific pizza
I looked up so many examples to try to figure out how to do this, but I couldn't. Thank you!
If you had a class which contained the information related to a pizza, let's call it Pizza, you could create a List(Of Pizza). That list can be iterated over once its data has been entered, for example if the user clicked a button to calculate the price.
Public Class Form1
Dim pizzas As New List(Of Pizza)
Public Class Pizza
Public Property QuantitySelector As NumericUpDown
Public Property UnitPrice As Decimal
Public Property Name As String
Public ReadOnly Property Quantity As Integer
Get
Return Convert.ToInt32(QuantitySelector.Value)
End Get
End Property
Sub New()
' Empty constructor
End Sub
Sub New(name As String, quantitySelector As NumericUpDown, unitPrice As Decimal)
Me.QuantitySelector = quantitySelector
Me.UnitPrice = unitPrice
Me.Name = name
End Sub
End Class
Private Sub bnCalcPrice_Click(sender As Object, e As EventArgs) Handles bnCalcPrice.Click
Dim sb As New Text.StringBuilder
For Each pz In pizzas
If pz.Quantity > 0 Then
sb.Append(vbNewLine & pz.Name & vbTab & vbTab & pz.Quantity & vbTab & pz.UnitPrice.ToString("c1") & vbTab & vbTab & (pz.Quantity * pz.UnitPrice).ToString("c1") & vbNewLine)
End If
Next
txtSummary.Text = sb.ToString()
End Sub
Private Sub InitPizzas()
Dim regularPrice = 8.5D ' Use Decimal values for money.
Dim premiumPrice = 13.5D
pizzas.Add(New Pizza("Hawaiian", NUD_Hawaiian, premiumPrice))
pizzas.Add(New Pizza("Americano", NUD_Americano, premiumPrice))
' etc.
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
InitPizzas()
End Sub
End Class
You could add code to add up the individual prices for each type of pizza too.
I also created a solution for you. Andrew has replied in the meantime while I was busy but I don't want to withhold that from you.
Like Andrew said, I would change the whole concept. I wrote a class with the most important properties of a pizza. You can change the amount in your restaurant kitchen. The data is saved in a List(of ClassPizza). As Andrew said, you can then iterate over this list and take advantage of the properties. For example sort by property xy. Maybe by best-before dates?
You can save the data in a text file. (Of course, it can be done better / differently but we don't want to exaggerate today). These data are read in when the program starts. (The very first time there is of course no data, just click on ‘cancel’ in the OpenfileDialog).
When new goods arrive, you can click on the button "bring new pizzas in store" and enter everything. A second form opens for this. Care is taken to ensure that no input errors are made (for example, quantity 0 makes no sense – the text then turns red).
The current stock is displayed in the 12 text boxes.
This is Form1.vb:
Imports Microsoft.VisualBasic.ControlChars
Imports Microsoft.WindowsAPICodePack.Dialogs
Public NotInheritable Class FormMain
Private ReadOnly Deu As New System.Globalization.CultureInfo("de-DE") ' change this to your language, for example "en-GB"
Private ReadOnly All_my_pizzas_List As New List(Of ClassPizza)
Private Sub FormMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each tb As TextBox In Me.Controls.OfType(Of TextBox)
tb.Text = "0"
Next
End Sub
Private Sub FormMain_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
Dim Path As String
Using OFD1 As New CommonOpenFileDialog
OFD1.Title = "pick file to open"
OFD1.Filters.Add(New CommonFileDialogFilter("Text file", ".txt"))
OFD1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
If OFD1.ShowDialog() = CommonFileDialogResult.Ok Then
Path = OFD1.FileName
Else
Return
End If
End Using
'read all Text
Dim RAT() As String = System.IO.File.ReadAllLines(Path, System.Text.Encoding.UTF8)
If RAT.Length = 0 Then Return
For i As Integer = 1 To RAT.Length - 3 Step 1
If RAT(i) = "#" Then
All_my_pizzas_List.Add(New ClassPizza(CType(RAT(i + 1), ClassPizza.Types_of_pizza), CUShort(RAT(i + 2)), CDec(RAT(i + 3))))
End If
Next
Update_Textboxes()
End Sub
Private Sub Update_Textboxes()
Dim NUD_Pepperoni, NUD_Hawaiian, NUD_Americano, NUD_TacoFiesta, NUD_Margherita, NUD_BeefOnion, NUD_BNY, NUD_MML, NUD_IL, NUD_GSS, NUD_AC, NUD_TMC As Integer
For Each piz As ClassPizza In All_my_pizzas_List
Select Case piz.Type_of_pizza
Case ClassPizza.Types_of_pizza.NUD_Pepperoni
NUD_Pepperoni += 1
Case ClassPizza.Types_of_pizza.NUD_Hawaiian
NUD_Hawaiian += 1
Case ClassPizza.Types_of_pizza.NUD_Americano
NUD_Americano += 1
Case ClassPizza.Types_of_pizza.NUD_TacoFiesta
NUD_TacoFiesta += 1
Case ClassPizza.Types_of_pizza.NUD_Margherita
NUD_Margherita += 1
Case ClassPizza.Types_of_pizza.NUD_BeefOnion
NUD_BeefOnion += 1
Case ClassPizza.Types_of_pizza.NUD_BNY
NUD_BNY += 1
Case ClassPizza.Types_of_pizza.NUD_MML
NUD_MML += 1
Case ClassPizza.Types_of_pizza.NUD_IL
NUD_IL += 1
Case ClassPizza.Types_of_pizza.NUD_GSS
NUD_GSS += 1
Case ClassPizza.Types_of_pizza.NUD_AC
NUD_AC += 1
Case ClassPizza.Types_of_pizza.NUD_TMC
NUD_TMC += 1
Case Else
Exit Select
End Select
Next
TextBox_Pepperoni.Text = NUD_Pepperoni.ToString(Deu)
TextBox_Hawaiian.Text = NUD_Hawaiian.ToString(Deu)
TextBox_Americano.Text = NUD_Americano.ToString(Deu)
TextBox_TacoFiesta.Text = NUD_TacoFiesta.ToString(Deu)
TextBox_Margherita.Text = NUD_Margherita.ToString(Deu)
TextBox_BeefOnion.Text = NUD_BeefOnion.ToString(Deu)
TextBox_BNY.Text = NUD_BNY.ToString(Deu)
TextBox_MML.Text = NUD_MML.ToString(Deu)
TextBox_IL.Text = NUD_IL.ToString(Deu)
TextBox_GSS.Text = NUD_GSS.ToString(Deu)
TextBox_AC.Text = NUD_AC.ToString(Deu)
TextBox_TMC.Text = NUD_TMC.ToString(Deu)
End Sub
Private Sub Button_toStore_Click(sender As Object, e As EventArgs) Handles Button_toStore.Click
Using FNP As New Form_new_pizza
FNP.GetData()
If FNP.ShowDialog = DialogResult.Yes Then
For i As UInt16 = 0US To FNP.Amount - 1US Step 1US
All_my_pizzas_List.Add(New ClassPizza(CType(FNP.SI, ClassPizza.Types_of_pizza), 1US, FNP.price))
Next
End If
End Using
Update_Textboxes()
End Sub
Private Sub Button_change_values_Click(sender As Object, e As EventArgs) Handles Button_change_values.Click
' this is still empty
End Sub
Private Sub Button_Save_Click(sender As Object, e As EventArgs) Handles Button_Save.Click
'-------------------------------------------------------------------------------------------------------------
' User can choose where to save the database text file and the program will save it.
'-------------------------------------------------------------------------------------------------------------
Dim Path As String
Using SFD1 As New CommonSaveFileDialog
SFD1.Title = "write data into text file"
SFD1.Filters.Add(New CommonFileDialogFilter("Text file", ".txt"))
SFD1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
If SFD1.ShowDialog() = CommonFileDialogResult.Ok Then
Path = SFD1.FileName & ".txt"
Else
Return
End If
End Using
Using textfile As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(Path, True, System.Text.Encoding.UTF8)
textfile.WriteLine("Status of this file [dd.mm.yyyy hh:mm:ss]: " & Date.Now.ToString("G", Deu))
For Each pizza As ClassPizza In All_my_pizzas_List
textfile.WriteLine("#") ' Marker
textfile.WriteLine(pizza.Type_of_pizza)
textfile.WriteLine(pizza.stored_amount)
textfile.WriteLine(pizza.price)
Next
textfile.Close()
End Using
End Sub
End Class
This is the code of the ClassPizza.vb
Public NotInheritable Class ClassPizza
Public Enum Types_of_pizza
NUD_Pepperoni
NUD_Hawaiian
NUD_Americano
NUD_TacoFiesta
NUD_Margherita
NUD_BeefOnion
NUD_BNY
NUD_MML
NUD_IL
NUD_GSS
NUD_AC
NUD_TMC
End Enum
Public Type_of_pizza As Types_of_pizza
Public stored_amount As UInt16 = 0US
''' <summary>
''' in $
''' </summary>
Public price As Decimal
Public Sub New(ByVal type As Types_of_pizza, ByVal storedAmount As UInt16, price As Decimal)
Me.Type_of_pizza = type
Me.stored_amount = storedAmount
Me.price = price
End Sub
End Class
And this is the code of that second Form (Form_new_pizza.vb)
Public NotInheritable Class Form_new_pizza
Public Amount As UInt16
Public price As Decimal
Public SI As Integer
Public Sub GetData()
For Each _item As Object In [Enum].GetValues(GetType(ClassPizza.Types_of_pizza))
ListBox1.Items.Add(_item)
Next
End Sub
Private Sub Form_new_pizza_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub TextBox_Amount_TextChanged(sender As Object, e As EventArgs) Handles TextBox_Amount.TextChanged
Dim success As Boolean = UInt16.TryParse(TextBox_Amount.Text, Amount)
If success AndAlso Amount > 0US Then
TextBox_Amount.ForeColor = Color.FromArgb(0, 200, 0) 'Green
Else
TextBox_Amount.ForeColor = Color.Red
End If
End Sub
Private Sub TextBox_price_TextChanged(sender As Object, e As EventArgs) Handles TextBox_price.TextChanged
Dim success As Boolean = Decimal.TryParse(TextBox_price.Text, price)
If success Then
TextBox_price.ForeColor = Color.FromArgb(0, 200, 0) 'Green
Else
TextBox_price.ForeColor = Color.Red
End If
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
If ListBox1.SelectedIndex <> (-1) Then
SI = ListBox1.SelectedIndex
End If
End Sub
Private Sub Button_OK_Click(sender As Object, e As EventArgs) Handles Button_OK.Click
If SI <> (-1) AndAlso Amount > 0US Then
Me.DialogResult = DialogResult.Yes
Else
Me.DialogResult = DialogResult.No
End If
End Sub
End Class
Of course, one can expand everything and do it better than me, but you can start, and understand the concept. 😉
By the way
You should set ‘Option Strict’ to On in the project properties so that you are advised to convert data types. Also set ‘Option Infer’ to Off so that you always have to write down the data type ("As Integer", "As Double", ...). The latter, however, is a matter of taste.
Also, you should remove the VB6 namespace as VB6 features are deprecated.
If you need control characters (such as NewLine), you can write Imports Microsoft.VisualBasic.ControlChars
.
====================================
Please note that I am using a FileDialog that I downloaded from Visual Studios' own Nuget Package Manager. See image. You don't have to do that, but I prefer this FileDialog because it offers more options than the one that is already included.

i am trying to read a text file in visual basics but i am not able to store the details in the array it gives errors

Dim EmpId(100) As String
Dim Lastname(100) As String
Dim firstname(100) As String
Dim hrs(100) As Integer
Dim min(100) As Integer
Dim counter As Integer
Dim i As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'declare variables
Dim result As DialogResult 'what did the user choose in the open dialog (open or cancel)
Dim strFileName As String 'store file path of the selected file
Dim strRecord As String
Dim sreStreamReader As IO.StreamReader
Dim strFieldValues(100) As String 'to store extracted field values.
Try
result = filebrowser.ShowDialog
If result = Windows.Forms.DialogResult.OK Then
strFileName = filebrowser.FileName
'create a StreamReader object by opening the file for input
sreStreamReader = IO.File.OpenText(strFileName)
counter = 0
i = 0
Do While sreStreamReader.Peek() <> -1
strRecord = sreStreamReader.ReadLine()
strFieldValues = strRecord.Split(",")
EmpId(counter) = strFieldValues(i) & firstname(counter) = strFieldValues(i) & Lastname(counter) = strFieldValues(i) _
& hrs(counter) = strFieldValues(i) & min(counter) = strFieldValues(i)
counter = counter + 1
i = i + 1
Loop
Dim j As Integer
For j = 0 To j < counter Step +1
Label1.Text = EmpId(j) & firstname(j) & Lastname(j) & hrs(j) & min(j)
Next
sreStreamReader.Close()
End If
Catch exFile As IO.FileNotFoundException
'processed when the file cannot be found
MessageBox.Show("Cannot locate the file.", _
"FileopenDialog", MessageBoxButtons.OK, _
MessageBoxIcon.Information)
' Catch ex As Exception
'handles any other errors
' MessageBox.Show(ex.Message, "FileopenDialog", _
' MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
I am assuming that your text file would look like this if opened in notepad.
1,Smith,Mary,7,45
2,Jones,Bill, 8,15
3,Mathew,Mark,6, 20
4,Luke,John,9,30
Notice there are no spaces. If there are spaces you may have to use .Trim on the strings.
I have a class called Employee. In the class there is a custom constructor (the Sub New) which sets all the appropriate properties. The values will come from the text file as you will see in a minute.
Then in the buttton click event a list of the type Employee is created.
Dim EmpList As New List(Of Employee)
It can hold objects of the type Employee. I use a `List(0f T) instead of an array because I don't have to know ahead of time how many lines are in the file.
The .ReadAllLines method of the File object returns an array containing each line in the file as an element of the array. Loop through the lines array calling .Split on each line which returns an array presumably containing each of the fields you are interested in. Each element is sent to the constructor of Employee and the resulting new Employee is added to the list. If there are extraneous spaces in the file this is where you may need to call .Trim to get rid of them
Finally, I have added a DataGridView to the form at design time. Set the .DataSource property to the list of employees and your data is displayed in the grid with headers.
Public Class Employee
Public Property ID As String
Public Property LasName As String
Public Property FirstName As String
Public Property Hours As Integer
Public Property Minutes As Integer
Public Sub New(iden As String, lname As String, fname As String, hr As Integer, mn As Integer)
ID = iden
LasName = lname
FirstName = fname
Hours = hr
Minutes = mn
End Sub
End Class
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim EmpList As New List(Of Employee)
Try
Dim result = OpenFileDialog1.ShowDialog
If Not result = Windows.Forms.DialogResult.OK Then
MessageBox.Show("No file selected")
End If
Dim strFileName = OpenFileDialog1.FileName
Dim lines = IO.File.ReadAllLines(strFileName)
For Each line In lines
Dim strFieldValues = line.Split(","c)
EmpList.Add(New Employee(strFieldValues(0), strFieldValues(1), strFieldValues(2), CInt(strFieldValues(3)), CInt(strFieldValues(4))))
Next
DataGridView1.DataSource = EmpList
Catch exFile As IO.FileNotFoundException
MessageBox.Show("Cannot locate the file.", "FileopenDialog", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
End Sub

Parsing String into an Array (VB)

I have tried to make a program that would parse a raw list from Chrome://policy (input by RichTextbox) into a text array, then dump it into another RichTextbox. All of the raw string are exactly 32 characters long, followed by a comma. Here is the code:
Public Class Form1
Dim tempExt As String
Dim extsHandled As Integer
Dim numOfExts As Integer
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If RichTextBox1.Text = "" Then
MsgBox("Please enter the raw extensions from Chrome://policy")
Else
RichTextBox3.Text = RichTextBox1.Text
numOfExts = TextBox1.Text
Dim place As Integer = 0
Dim exts(150) As String
While extsHandled < numOfExts
tempExt = RichTextBox1.Text.Substring(0, 32)
exts(place) = tempExt
RichTextBox1.Text.Remove(0, 33)
place = place + 1
extsHandled = extsHandled + 1
End While
Dim newPlace As Integer = 0
While newPlace < numOfExts
RichTextBox2.AppendText(exts(newPlace))
newPlace = newPlace + 1
RichTextBox2.AppendText(" ")
End While
End If
End Sub
End Class
Most of it works, but it would seem something is going wrong with removing the characters from the richtextbox, as when I run it, it only parses the first part of the string over and over:
Am I doing something wrong?
If it's always like that you can do it like this:
RichTextBox3.Text = RichTextBox1.Text.Replace(",", vbNewLine)
The #3 is your result, while #1 is original right?
Ah yeah, you can count how many there simply by
RichTextBox2.Text= RichTextBox1.Text.Split({","}, StringSplitOptions.RemoveEmptyEntries).Count.ToString
This line returns a new string:
RichTextBox1.Text.Remove(0, 33)
It does not modify the textbox in place. The next iteration through the loop, you're still working with the original value, looking at the same set of 32 characters at the beginning of the string.
Additionally, nothing in this code initializes the extsHandled variable. You should turn on Option Strict, which helps catch that kind of error. Running of Option Strict off is poor practice. You should also give a meaningful name to any control you will actually reference from code.
It's not clear to me right now the exact format. If it's all on the same line (no line break characters as part of the string, even if it wraps), this should work:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If String.IsNullOrWhitespace(RichTextBox1.Text) Then
MsgBox("Please enter the raw extensions from Chrome://policy")
Exit Sub
End If
RichTextBox3.Text = RichTextBox1.Text
Dim exts() As String
Using rdr As New TextFieldParser(RichTextBox1.Text)
rdr.TextFieldType = FileIO.FieldType.Delimited
rdr.Delimiters = New String() {","}
exts = rdr.ReadFields()
End Using
For Each ext As String In exts
RichTextBox2.AppendText(ext)
Next ext
RichTextBox1.Text = ""
End Sub
The problem is this code doesn't do anything. The array is gone when the method ends. Consider making the array a property of the class, or having method that returns the array as the result.
You can also look at this, to save typing into the textbox, though it's just a starting point:
Public Function GetChromeExtensionKeys() As IEnumerable(Of String)
Dim BasePath As String =
EndEnvironment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
BasePath = Path.Combine(BasePath, "Google\Chrome\User Data")
Dim dflt As String = Path.Combine(BasePath, "Default\Extensions")
Dim profileExts() As String = Directory.GetDirectories(BasePath, "Profile *").
Select(Function(p) Path.Combine(p, "Extensions"))
Dim result As New List(Of String)()
result.AddRange(Directory.GetDirectories(dflt))
For Each folder As String In profiles
result.AddRange(Directory.GetDirectories(folder))
Next folder
Return result.Select(Function(e) Path.GetFileName(e)).Distinct()
Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each ext As String In GetChromeExtensionKeys()
RichTextBox2.AppendText(ext)
Next ext
End Sub

print images from a folder in vb .net with 8 images per page

i select a folder using vb .net.my code is like below--
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If (FolderBrowserDialog1.ShowDialog() = DialogResult.OK) Then
TextBox1.Text = FolderBrowserDialog1.SelectedPath
End If
End Sub
But the problem is i don't have any idea about displaying the images(8 images Per page)
VB.Net Version:
Since you want to create print preview, I would suggest you to create a new Form just for the print preview and track the PageNumber which the user inputs
Dim pageNumber As Integer = 0 'start from 0, but change this according to the user input accordingly
You could get the list of files from the given folder by using Directory.GetFiles in the System.IO
Dim rawpaths As List(Of String) = Directory.GetFiles(folder).ToList() 'This gets all files, not only images
You may need to provide a list of acceptable image extension according to this.
Dim validImageFormat As New List(Of String) From {"jpg", "bmp", "png", "jpeg", "gif", "tiff"}
And filter your file results such that they only contains acceptable image results like this (using Split method, Contains, etc...)
Dim paths As List(Of String) = New List(Of String)
For Each rawpath As String In rawpaths
Dim rawwords As String() = rawpath.Split(".") 'split the rawpath, the important is the last element, which is the file extension
If (validImageFormat.Contains(rawwords(rawwords.Length - 1))) Then 'the rawpath is a valid image path
paths.Add(rawpath) 'this is a valid image path
End If
Next
Then, in your print preview Form you may need to list your 8 ListBoxes to ease you to control the display later as well as to handle the case where the number of the images are not multiplication of 8
Dim pbList As List(Of PictureBox) = New List(Of PictureBox)
Private Sub printPreviewForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
pbList.Add(PictureBox1) 'list your picture box will help you later
pbList.Add(PictureBox2)
pbList.Add(PictureBox3)
pbList.Add(PictureBox4)
pbList.Add(PictureBox5)
pbList.Add(PictureBox6)
pbList.Add(PictureBox7)
pbList.Add(PictureBox8)
End Sub
Then, you need to determine, how many pictures are to be shown (min of 1, max of 8, based on the PageNumber)
If (pageNumber * 8 > paths.Count) Then 'exceeds the possible image display
Return 'this is not allowed, do something
End If
Dim minPathNo As Integer = pageNumber * 8 'get the min and max for later display
Dim maxPathNo As Integer = Math.Min(pageNumber * 8 + 7, paths.Count - 1)
Finally, to display, you can use Image.FromFile() method to load the image file from your folder plus using the minPathNo and maxPathNo declared before to show the images safely
If (pageNumber * 8 > paths.Count) Then 'exceeds the possible image display
Return 'this is not allowed, do something
End If
Dim minPathNo As Integer = pageNumber * 8
Dim maxPathNo As Integer = Math.Min(pageNumber * 8 + 7, paths.Count - 1)
For i As Integer = minPathNo To minPathNo + 7
Dim pbIndex As Integer = i - minPathNo
If i <= maxPathNo Then
pbList(pbIndex).Image = Image.FromFile(paths(i)) 'display existing image
Else
pbList(pbIndex).Image = Nothing 'don't display non-existing image
End If
Next
Edit:
Suppose your form looks like this:
Then this is how your code would look like in just one form. In your case, you have to make two forms:
Imports System.IO
Public Class Form1
Dim folder As String = "C:\MyPics"
Dim validImageFormat As New List(Of String) From {"jpg", "bmp", "png", "jpeg", "gif", "tiff"}
Dim pbList As List(Of PictureBox) = New List(Of PictureBox)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim rawpaths As List(Of String) = Directory.GetFiles(folder).ToList() 'Assuming all the file is image
Dim paths As List(Of String) = New List(Of String)
For Each rawpath As String In rawpaths
Dim rawwords As String() = rawpath.Split(".") 'split the rawpath, the important is the last element, which is the file extension
If (validImageFormat.Contains(rawwords(rawwords.Length - 1))) Then 'the rawpath is a valid image path
paths.Add(rawpath) 'this is a valid image path
End If
Next
Dim pageNumber As Integer = NumericUpDown1.Value
If (pageNumber * 8 > paths.Count) Then 'exceeds the possible image display
Return 'this is not allowed, do something
End If
Dim minPathNo As Integer = pageNumber * 8
Dim maxPathNo As Integer = Math.Min(pageNumber * 8 + 7, paths.Count - 1)
For i As Integer = minPathNo To maxPathNo
Dim currentPictureBox As Integer = i - minPathNo
pbList(currentPictureBox).Image = Image.FromFile(paths(i))
Next
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
pbList.Add(PictureBox1)
pbList.Add(PictureBox2)
pbList.Add(PictureBox3)
pbList.Add(PictureBox4)
pbList.Add(PictureBox5)
pbList.Add(PictureBox6)
pbList.Add(PictureBox7)
pbList.Add(PictureBox8)
End Sub
End Class
And you only need to change the numericUpDown (simulating your page` to 0, 1, 2, etc...)

Multiple Search Criteria (VB.NET)

So my problem is:
I have a List of a custom Type {Id as Integer, Tag() as String},
and i want to perform a multiple-criteria search on it; eg:
SearchTags={"Document","HelloWorld"}
Results of the Search will be placed a ListBox (ListBox1) in this format:
resultItem.id & " - " & resultItem.tags
I already tried everything i could find on forums, but it didn't work for me (It was for db's or for string datatypes)
Now, i really need your help. Thanks in advance.
For Each MEntry As EntryType In MainList
For Each Entry In MEntry.getTags
For Each item As String In Split(TextBox1.Text, " ")
If Entry.Contains(item) Then
If TestIfItemExistsInListBox2(item) = False Then
ListBox1.Items.Add(item & " - " & Entry.getId)
End If
End If
Next
Next
Next
Example Custom Array:
(24,{"snippet","vb"})
(32,{"console","cpp","helloworld"})
and so on...
I searched for ("Snippet vb test"):
snippet vb helloWorld - 2
snippet vb tcpchatEx - 16
cs something
test
So, i'll get everything that contains one of my search phrases.
I expected following:
snippet vb tcp test
snippet vb dll test
snippet vb test metroui
So, i want to get everything that contains all my search phrases.
My entire, code-likely class
Imports Newtonsoft.Json
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Dim MainList As New List(Of EntryType)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MainList.Clear()
Dim thr As New Threading.Thread(AddressOf thr1)
thr.SetApartmentState(Threading.ApartmentState.MTA)
thr.Start()
End Sub
Delegate Sub SetTextCallback([text] As String)
Private Sub SetTitle(ByVal [text] As String) ' source <> mine
If Me.TextBox1.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetTitle)
Me.Invoke(d, New Object() {[text]})
Else
Me.Text = [text]
End If
End Sub
Sub thr1()
Dim linez As Integer = 1
Dim linex As Integer = 1
For Each line As String In System.IO.File.ReadAllLines("index.db")
linez += 1
Next
For Each line As String In System.IO.File.ReadAllLines("index.db")
Try
Application.DoEvents()
Dim a As saLoginResponse = JsonConvert.DeserializeObject(Of saLoginResponse)(line) ' source <> mine
Application.DoEvents()
MainList.Add(New EntryType(a.id, Split(a.tags, " ")))
linex += 1
SetTitle("Search (loading, " & linex & " of " & linez & ")")
Catch ex As Exception
End Try
Next
SetTitle("Search")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim searchTags() As String = TextBox1.Text.Split(" ")
Dim query = MainList.Where(Function(et) et.Tags.Any(Function(tag) searchTags.Contains(tag))).ToList
For Each et In query
ListBox1.Items.Add(et.Id)
Next
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) ' test
MsgBox(Mid(ListBox1.SelectedItem.ToString, 1, 6)) ' test
End Sub 'test, removeonrelease
End Class
Public Class EntryType
Public Property Id As Integer
Public Property Tags() As String
Public Sub New(ByVal _id As Integer, ByVal _tags() As String)
Me.Id = Id
Me.Tags = Tags
End Sub
Public Function GetTags() As String
'to tell the Listbox what to display
Return Tags
End Function
Public Function GetId() As Integer
'to tell the Listbox what to display
Return Id
End Function
End Class
I also edited your EntryType class; I added a constructor, removed toString and added GetTags and GetID.
Example "DB" im working with ("db" as "index.db" in exec dir):
{"tags":"vb.net lol test qwikscopeZ","id":123456}
{"tags":"vb.net lol test","id":12345}
{"tags":"vb.net lol","id":1234}
{"tags":"vb.net","id":123}
{"tags":"cpp","id":1}
{"tags":"cpp graphical","id":2}
{"tags":"cpp graphical fractals","id":3}
{"tags":"cpp graphical fractals m4th","id":500123}
Error:
Debugger:Exception Intercepted: _Lambda$__1, Form2.vb line 44
An exception was intercepted and the call stack unwound to the point before the call from user code where the exception occurred. "Unwind the call stack on unhandled exceptions" is selected in the debugger options.
Time: 13.11.2014 03:46:10
Thread:<No Name>[5856]
Here is a Lambda query. The Where filters on a predicate, since Tags is an Array you can use the Any function to perform a search based on another Array-SearchTags. You can store each class object in the Listbox since it stores Objects, you just need to tell it what to display(see below).
Public Class EntryType
Public Property Id As Integer
Public Property Tags() As As String
Public Overrides Function ToString() As String
'to tell the Listbox what to display
Return String.Format("{0} - {1}", Me.Id, String.Join(Me.Tags, " "))
End Function
End Class
Dim searchTags = textbox1.Text.Split(" "c)
Dim query = mainlist.Where(Function(et) et.Tags.Any(Function(tag) searchTags.Contains(tag))).ToList
For Each et In query
Listbox1.Items.Add(et)
Next