How to print main, customer and duplicate copy in Crystal Report - vb.net

How to print first time Main Copy
second time Customer Copy
third or more time Duplicate Copy
My requirement is as in the image below:

VB Code
At first do Import
Imports System.Web.UI.WebControls
Public Sub ShowReport(ByVal MyReport As CrystalDecisions.CrystalReports.Engine.ReportDocument, ByVal filterstring As String, ByVal CrystalReportViewer As CrystalDecisions.Windows.Forms.CrystalReportViewer)
Dim myLogonInfo As New CrystalDecisions.Shared.TableLogOnInfo
Dim myTable As Table
For Each myTable In MyReport.Database.Tables
myLogonInfo = myTable.LogOnInfo
'myLogonInfo.ConnectionInfo.ServerName = Application.StartupPath & "\" & "data.mdb"
myLogonInfo.ConnectionInfo.ServerName = My.Settings.RptserverPath.ToString
myLogonInfo.ConnectionInfo.DatabaseName = My.Settings.Database.ToString
myLogonInfo.ConnectionInfo.UserID = My.Settings.DBUser.ToString
myLogonInfo.ConnectionInfo.Password = My.Settings.DBPass.ToString
myTable.ApplyLogOnInfo(myLogonInfo)
Next myTable
End Sub
Private Sub SimpleButton4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButton4.Click
For reportType As Integer = 1 To 3
Dim MyReport As CrystalDecisions.CrystalReports.Engine.ReportDocument = New RecipeWithOutCostingSheet
MyReport.SetParameterValue("paramReportType", reportType)
PrintReport(MyReport, filterstring, CrystalReportViewer1, PrintDialog1)
Next
End Sub
Crystal report Formula Create formula name paramReportType
Select {?paramReportType}
Case 1 :
"Main Copy"
Case 2 :
"Customer Copy"
Default :
"Duplicate Copy"
Put on your Report Location.

In your code
Dim rpt As New CrystalDecisions.CrystalReports.Engine.ReportDocument
rpt.Load("<report name>")
rpt.SetDataSource(your datasource)
For reportType As Integer = 1 To 3
rpt.SetParameterValue("paramReportType", reportType)
' show your report in a dialog window
ShowReport(rpt)
Next
Public Sub ShowReport(ByRef oRpt As Object)
Using frm As New ReportViewer
With frm
.Icon = frmMain.Icon
.Report = oRpt
.ShowDialog()
End With
End Using
End Sub
Inside ReportViewer form (with 1 CrystalReportViewer control named crv)
Public Class ReportViewer
Dim oReport As Object
Public WriteOnly Property Report() As Object
Set(ByVal value As Object)
oReport = value
End Set
End Property
Private Sub ReportViewer_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Try
Me.Cursor = Cursors.WaitCursor
crv.ReportSource = oRpt
Catch ex As Exception
Msgbox(ex.Message)
Finally
Me.Cursor = Cursors.Default
End Try
End Sub
End Class
In your report, create a parameter value named paramReportType with a type of Number.
Then, also inside your report, create a formula field (I'm using Basic syntax)
select case {?paramReportType}
case 1
formula = "Main Copy"
case 2
formula = "Customer Copy"
case 3
formula = "Duplicate Copy"
end select
Then add the formula field to your report, instead of a Text object.

Related

vb.net save textbox values for later use

I use a textbox in my form to search for words in pdf files. I want to save these search words somewhere for later use. So when the user types a letter in the textbox there will be a pulldown with previous searched words. Something like windows does in Explorer.
Does anyone have an example or is someone familiar with this?
You can store and retrieve a list of search words in an application settings entry of type StringCollection as the data source of the TextBox.AutoCompleteCustomSource property.
Add new entry
Select YourAppName Properties from the Project menu.
Select the Settings tab.
Add new entry in the Name column, say: SearchWords.
From the Type column, select System.Collections.Specialized.StringCollection.
Close the dialog and save.
Retrieve the search words
In the Form's constructor or Load event, say you have a search TextBox named txtSearch:
' +
Imports System.Linq
Imports System.Collections.Specialized
Private Sub YourForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If My.Settings.SearchWords Is Nothing Then
My.Settings.SearchWords = New StringCollection
End If
Dim acc As New AutoCompleteStringCollection
acc.AddRange(My.Settings.SearchWords.Cast(Of String).ToArray())
txtSearch.AutoCompleteMode = AutoCompleteMode.Suggest
txtSearch.AutoCompleteSource = AutoCompleteSource.CustomSource
txtSearch.AutoCompleteCustomSource = acc
End Sub
Update the collection
You need to add the new words whenever you perform a search:
' When you click a search button...
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
AddSearchWord()
End Sub
' If you call the search routine when you press the Enter key...
Private Sub txtSearch_KeyDown(sender As Object, e As KeyEventArgs) Handles txtSearch.KeyDown
If e.KeyCode = Keys.Enter Then
AddSearchWord()
End If
End Sub
' Update the collection...
Private Sub AddSearchWord()
If txtSearch.Text.Trim.Length = 0 Then Return
If Not txtSearch.AutoCompleteCustomSource.Contains(txtSearch.Text) Then
If txtSearch.AutoCompleteCustomSource.Count > 10 Then
txtSearch.AutoCompleteCustomSource.RemoveAt(
txtSearch.AutoCompleteCustomSource.Count - 1)
End If
txtSearch.AutoCompleteCustomSource.Insert(0, txtSearch.Text)
End If
End Sub
Save the collection
Update the SearchWord string collection when you close the Form:
Private Sub YourForm_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
My.Settings.SearchWords = New StringCollection
My.Settings.SearchWords.AddRange(txtSearch.AutoCompleteCustomSource.Cast(Of String).ToArray)
My.Settings.Save()
End Sub
Demo
I found some code Saving text box values to a file to load again that I changed to my needs. It saves the content of my ComboBox1 to a textfile when I click my Submit button. When I load the form the textfile is read and loaded into the ComboBox1 as previous used searches.
'now save the search word to our textfile
PresetName = TextBoxFreeText.Text
If PresetName <> "" Then
TextBoxFreeText.Items.Add(PresetName)
Call SaveData(PresetName)
End If
The code to load the saved values:
Private Sub ReadData()
If My.Computer.FileSystem.FileExists(FilePath) = True Then
myReader = New StreamReader(FilePath)
Dim myText = myReader.ReadLine
While myText IsNot Nothing
listPreset.Add(myText)
myText = myReader.ReadLine
End While
myReader.Close()
'Add Preset Names to ComboBox
If listPreset.Count > 0 Then
Dim PresetName As String
Dim index As Integer
For i = 0 To listPreset.Count - 1
index = listPreset.Item(i).IndexOf(",")
PresetName = Mid(listPreset.Item(i), 1, index)
TextBoxFreeText.Items.Add(PresetName)
Next
End If
End If
End Sub
The code to save the content of ComboBox1
Private Sub SaveData(ByVal PresetName As String)
Dim FileString As String = PresetName & ","
'Build File String
FileString &= TextBoxFreeText.Text & ","
listPreset.Add(FileString)
myWriter = New StreamWriter(FilePath)
For i = 0 To listPreset.Count - 1
myWriter.WriteLine(listPreset.Item(i))
Next
myWriter.Close()
End Sub
There are still two things I want to change. I will ask in a new question.
prevent duplicate search string to be entered in the textfile.
set a maximum to the search string loaded in ComboBox1 (maybe 10 words)

VB.Net populating text boxes from text file

I'm creating an inventory management system where the data is stored in a text file. I'm able to save data to the text file, however on the tracker screen it should show current inventory such as: Manufacturer, Processor, Video, Form, RAM, etc. However, all my text boxes remain blank and I'm not sure why. It's not reading properly or updating the text.
frmTracker.vb
Private Sub txtManufacturer_TextChanged(sender As Object, e As EventArgs) Handles txtManufacturer.TextChanged
Dim objMyStreamReader = System.IO.File.OpenText("inventory.txt")
Dim strInventory = objMyStreamReader.ReadLine()
objMyStreamReader.Close()
txtManufacturer.AppendText(strInventory)
End Sub
This is how I'm currently saving the data to the text file.
frmItemEntry.vb
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim objMyStreamReader As System.IO.StreamReader
Dim objMyStreamWriter As System.IO.StreamWriter = System.IO.File.CreateText("inventory.txt")
Dim strInventory As String
objMyStreamWriter.WriteLine(txtManufacturerEntry.Text)
objMyStreamWriter.WriteLine(txtProcessorEntry.Text)
objMyStreamWriter.WriteLine(txtVideoEntry.Text)
objMyStreamWriter.WriteLine(txtFormEntry.Text)
objMyStreamWriter.WriteLine(txtRamEntry.Text)
objMyStreamWriter.WriteLine(txtVramEntry.Text)
objMyStreamWriter.WriteLine(txtHdEntry.Text)
objMyStreamWriter.WriteLine(chkWirelessEntry.CheckState)
objMyStreamWriter.Close()
Me.Close()
End Sub
Example from inventory.txt
Dell
i5
Nvidia
Desktop
8
4
600
0
To be honest, controls should never be used as the primary store for your data in a program. You should really be creating a class and a list of that class to store your data.
You can then read your data into the list from your file, and then, display it from there in your form.
There are several ways of navigating through the data and saving updates. The suggestion below uses buttons for next item and previous item, and a button to save update the file.
It's all pretty self explanatory, but if there's something your not sure about, please have a google and learn something new :-D
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ReadDataFile()
DisplayItem(0)
End Sub
Private Class InventoryItem
Public Property Manufacturer As String
Public Property Processor As String
Public Property Video As String
Public Property FormFactor As String
Public Property Ram As String
Public Property VRam As String
Public Property Hd As String
Public Property Wireless As CheckState
Public Sub New()
Manufacturer = ""
Processor = ""
Video = ""
FormFactor = ""
Ram = ""
VRam = ""
Hd = ""
Wireless = CheckState.Unchecked
End Sub
End Class
Dim Inventory As New List(Of InventoryItem)
Dim currentItemIndex As Integer
Private Sub ReadDataFile()
Using objMyStreamReader As New StreamReader("k:\inventory.txt")
Do Until objMyStreamReader.EndOfStream
Dim newItem As New InventoryItem
newItem.Manufacturer = objMyStreamReader.ReadLine()
newItem.Processor = objMyStreamReader.ReadLine()
newItem.Video = objMyStreamReader.ReadLine()
newItem.FormFactor = objMyStreamReader.ReadLine()
newItem.Ram = objMyStreamReader.ReadLine()
newItem.VRam = objMyStreamReader.ReadLine()
newItem.Hd = objMyStreamReader.ReadLine()
Dim wirelessValue As String = objMyStreamReader.ReadLine()
If wirelessValue = "0" Then
newItem.Wireless = CheckState.Unchecked
ElseIf wirelessValue = "1" Then
newItem.Wireless = CheckState.Checked
End If
Inventory.Add(newItem)
Loop
End Using
End Sub
Private Sub SaveDataFile()
Using objMyStreamWriter As New System.IO.StreamWriter("k:\inventory.txt", False)
For Each item As InventoryItem In Inventory
objMyStreamWriter.WriteLine(item.Manufacturer)
objMyStreamWriter.WriteLine(item.Processor)
objMyStreamWriter.WriteLine(item.Video)
objMyStreamWriter.WriteLine(item.FormFactor)
objMyStreamWriter.WriteLine(item.Ram)
objMyStreamWriter.WriteLine(item.VRam)
objMyStreamWriter.WriteLine(item.Hd)
If item.Wireless = CheckState.Checked Then
objMyStreamWriter.WriteLine("1")
Else
objMyStreamWriter.WriteLine(0)
End If
Next
End Using
End Sub
Private Sub DisplayItem(index As Integer)
With Inventory(index)
txtManufacturerEntry.Text = .Manufacturer
txtProcessorEntry.Text = .Processor
txtVideoEntry.Text = .Video
txtFormEntry.Text = .FormFactor
txtRamEntry.Text = .Ram
txtVramEntry.Text = .VRam
txtHdEntry.Text = .Hd
chkWirelessEntry.CheckState = .Wireless
End With
End Sub
Private Sub BtnUpdateItem_Click(sender As Object, e As EventArgs) Handles BtnUpdateItem.Click
With Inventory(currentItemIndex)
.Manufacturer = txtManufacturerEntry.Text
.Processor = txtProcessorEntry.Text
.Video = txtVideoEntry.Text
.FormFactor = txtFormEntry.Text
.Ram = txtRamEntry.Text
.VRam = txtVramEntry.Text
.Hd = txtHdEntry.Text
.Wireless = chkWirelessEntry.CheckState
End With
SaveDataFile()
End Sub
Private Sub BtnPreviousItem_Click(sender As Object, e As EventArgs) Handles BtnPreviousItem.Click
If currentItemIndex > 0 Then
currentItemIndex -= 1
DisplayItem(currentItemIndex)
End If
End Sub
Private Sub BtnNextItem_Click(sender As Object, e As EventArgs) Handles BtnNextItem.Click
If currentItemIndex < Inventory.Count - 1 Then
currentItemIndex -= 1
DisplayItem(currentItemIndex)
End If
End Sub
First change the format of your text file.
Dell,i5,Nvidia,Desktop,8,2,600,True
Acer,i7,Intel,Desktop,16,4,1GB,True
HP,Pentium,Diamond Viper,Desktop,4,2,200,False
Surface Pro,i7,Intel,Laptop,8,2,500,True
Each line is a record and each field in the record is separated by a comma (no spaces so we don't have to .Trim in code) (a space within a field is fine, notice Surface Pro).
Now it is easier to read the file in code.
This solution uses a BindingSource and DataBindings. This simplifies Navigation and editing and saving the data.
Public Class Form5
Private bs As BindingSource
Private dt As New DataTable
#Region "Set Up the Form"
Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddColumnsToDataTable()
FillDataTable()
AddDataBindings()
End Sub
Private Sub AddColumnsToDataTable()
'Prepare the DataTable to hold data
dt.Columns.Add("Manufacturer", GetType(String))
dt.Columns.Add("Processor", GetType(String))
dt.Columns.Add("Video", GetType(String))
dt.Columns.Add("Form", GetType(String))
dt.Columns.Add("RAM", GetType(String))
dt.Columns.Add("VRAM", GetType(String))
dt.Columns.Add("HD", GetType(String))
dt.Columns.Add("Wireless", GetType(Boolean))
End Sub
Private Sub FillDataTable()
'ReadAllLines returns an array of the lines in a text file
'inventory.txt is stored in the bin\Debug folder of your project
'This is the current directory so it does not require a full path.
Dim lines = File.ReadAllLines("inventory.txt")
'Now it is easy to split each line into fields by using the comma
For Each line As String In lines
'Split returns an array of strings with the value of each field
Dim items = line.Split(","c)
'Each item in the array can be added as a field to the DataTable row
dt.Rows.Add(items(0), items(1), items(2), items(3), items(4), items(5), items(6), CBool(items(7)))
'Notice that the last element is changed from a string to a boolean. This is
'the Wireless field which is bound to the check box. The string "True" or "False" is
'changed to a Boolean so it can be used as the .Checked property (see bindings)
Next
End Sub
Private Sub AddDataBindings()
'Create a new instance of the BindingSource class
bs = New BindingSource()
'Set the DataSource to the DataTable we just filled
bs.DataSource = dt
'Now you can set the bindings of each control
'The .Add method takes (Name of Property to Bind, the BindingSource to use, The Field name
'from the DataTable.
txtForm.DataBindings.Add("Text", bs, "Form")
txtHd.DataBindings.Add("Text", bs, "HD")
txtManufacturer.DataBindings.Add("Text", bs, "Manufacturer")
txtProcessor.DataBindings.Add("Text", bs, "Processor")
txtRam.DataBindings.Add("Text", bs, "RAM")
txtVideo.DataBindings.Add("Text", bs, "Video")
txtVram.DataBindings.Add("Text", bs, "VRAM")
'Notice on the CheckBox we are using the Checked property.
chkWireless.DataBindings.Add("Checked", bs, "Wireless")
End Sub
#End Region
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
'Add a blank row to the DataTable
'A Boolean is like a number, a String can be Nothing but a Boolean must
'have a value so we pass in False.
dt.Rows.Add(Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, False)
'Find the position of the last row
Dim i As Integer = bs.Count - 1
'Move to the new empty row
bs.Position = i
End Sub
#Region "Navigation Code"
Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
'The binding source Position determins where in the data you are
'It starts at zero
If bs.Position = 0 Then
MessageBox.Show("This is the first item.")
Return 'This exits the sub, you can use Exit Sub in vb
'but Return is common in other languages so it is good to learn
Else
'As the position of the BindingSource changes the boud TextBoxes
'change their data.
bs.Position = bs.Position - 1
End If
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
' If you are not at the end of the list, move to the next item
' in the BindingSource.
If bs.Position + 1 < bs.Count Then
bs.MoveNext()
' Otherwise, move back to the first item.
Else
bs.MoveFirst()
End If
End Sub
#End Region
#Region "Save the Data"
Private Sub SaveDataTable()
'Resave the whole file if this was a real app you would use a database
Dim sb As New StringBuilder
'A string builder keeps the code from creating lots of new strings
'Strings are immutable (can't be changed) so every time you think you are
'changing a string, you are actually creating a new one.
'The string builder is mutable (changable)
For Each row As DataRow In dt.Rows
'The ItemsArray returns an array of objects containing all the
'values in each column of the data table.
Dim rowValues = row.ItemArray
'This is a bit of Linq magic that turns the values (objects) into strings
'Underneath it is performing a For loop on each object in the array
Dim strRowValues = From o In rowValues
Select Convert.ToString(o)
'Now that we have strings we can use the String.Join with the comma
'to get the format of the text file
sb.AppendLine(String.Join(",", strRowValues))
Next
'Finally we change the StringBuilder to a real String
'The inventory.txt is stored in the bin\Debug directory so it is current directory
'no additional path required
File.WriteAllText("inventory.txt", sb.ToString)
End Sub
Private Sub Form5_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
'Because our binding is two-way any additions or changes to the text
'in the text boxes or check box are reflected in the DataTable.
SaveDataTable()
End Sub
#End Region
End Class
Once you remove the comments, there is really very little code here. The #Region...#End Region tags make it easy to collapse code sections you are not working on and find areas quickly.

vb.net combobox to return value of another column

I have two comboboxes. The second one is dependant on the first. I then pass the selected values to a second form as objects. My code works perfectly up to here. But I also need to pass a third object to the second form (i.e. plaasnopass) based on the selection of the second combobox (i.e cmbPlaasnaam). This value however is in another column. My code below runs without errors , but the third value is not passed to the second form.
Public Class ParskaartjieKiesFrm
Dim obj As New Parskaartjies
Private Sub ParskaartjieKiesFrm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'SkeduleringDatabasisDataSet.wingrd13' table. You can move, or remove it, as needed.
Me.Wingrd13TableAdapter.Fill(Me.SkeduleringDatabasisDataSet.wingrd13)
With CmbAliasnaam
.BeginUpdate()
.AutoCompleteMode = AutoCompleteMode.SuggestAppend
.AutoCompleteSource = AutoCompleteSource.ListItems
Dim qry = From zc As SkeduleringDatabasisDataSet.wingrd13Row In SkeduleringDatabasisDataSet.wingrd13 _
Select zc.Aliasnaam Distinct Order By Aliasnaam
For Each ALIASNAAM As String In qry
.Items.Add(ALIASNAAM)
Next
.EndUpdate()
End With
With CmbPlaasnaam
.AutoCompleteMode = AutoCompleteMode.SuggestAppend
.AutoCompleteSource = AutoCompleteSource.ListItems
.Enabled = False
End With
End Sub
Private Sub CmbAliasnaam_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CmbAliasnaam.SelectedIndexChanged
obj.aliasnaampass = CmbAliasnaam.SelectedItem
With CmbPlaasnaam
.SelectedIndex = -1
.Items.Clear()
.Enabled = False
End With
If CmbAliasnaam.SelectedIndex > -1 Then
CmbPlaasnaam.BeginUpdate()
Dim Aliasnaam As String = CmbAliasnaam.Items(CmbAliasnaam.SelectedIndex).ToString
Dim qry = From zc As SkeduleringDatabasisDataSet.wingrd13Row In SkeduleringDatabasisDataSet.wingrd13 _
Where zc.Aliasnaam = ALIASNAAM Select zc.Plaasnaam Distinct _
Order By Plaasnaam
For Each plaasnaam As String In qry
CmbPlaasnaam.Items.Add(plaasnaam)
Next
If CmbPlaasnaam.Items.Count > 0 Then
CmbPlaasnaam.Enabled = True
End If
CmbPlaasnaam.EndUpdate()
End If
End Sub
Private Sub CmbPlaasnaam_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CmbPlaasnaam.SelectedIndexChanged
obj.plaasnaampass = CmbPlaasnaam.SelectedItem
obj.plaasnopass = CmbAliasnaam.SelectedValue
obj.Show()
Me.Close()
End Sub
End Class
How do I go about ?
Regards
According to your comment, I understood that you have combo box loaded from
select a from t
but this gives you single value, and you want to load
select a, b from t
and pass both values to next form.
It is helpful that you're using LINQ!! Modify it. But first declare new type
Public Class CboItem
Public Property Display As String
Public Property Value As String ' <-- any datatype
' .... any number of properties here
End Class
Dim qry =
(From zc As SkeduleringDatabasisDataSet.wingrd13Row
In SkeduleringDatabasisDataSet.wingrd13 _
Where zc.Aliasnaam = ALIASNAAM
Select New CboItem() With { .Display = zc.Plaasnaam, .Value = zs.[...] }).
Distinct(function(item)...).OrderBy(function(item)...)
CmbAliasnaam.DisplayMember = "Display"
CmbAliasnaam.ValueMember = "Value"
CmbAliasnaam.DataSource = qry.ToList()
Now you can pass to your form selected item or whatever you get out of it. for example
Dim item As CboItem = TryCast(CmbAliasnaam.SelectedItem, CboItem)
If item IsNot Nothing Then
frm.SetSelected(item.Display, item.Value, item.anyOtherProperty)
End If
' or
frm.SomeProperty = item
As you see, you can pass an object that you can store in combo box. It doesn't have to be string.

Importing a CSV into a combobox, then changing other things in VB

What I want to do is import a CSV file (called fwlist.txt), that looks like this:
modelname,power type,pic,part number,firmware, option1, option 1, etc
End result, i would like a combobox that shows the modelname, and when the model name is selected from the pulldown, it updates various labels and text boxes on the form with other information.
Here's what I have so far:
Dim filename As String = "fwlist.txt"
Dim pwrtype As String
Dim pic As String
Dim partnum As String
Dim lineread As String
Dim FirmwareName As String
Private Sub ReadFirmwaresLoad(sender As Object, e As EventArgs) Handles Me.Load
' Load the items into the NameComboBox list.
Dim ResponseDialogResult As DialogResult
Try
Dim FirmwareStreamReader As StreamReader = New StreamReader(filename)
' Read all the elements into the list.
Do Until FirmwareStreamReader.Peek = -1
lineread = FirmwareStreamReader.ReadLine()
Dim fields As String() = lineread.Split(",")
FirmwareName = fields(0) 'Take First Field
cbFW.Items.Add(FirmwareName)
'Set Text labels based on position in line.
pwrtype = fields(1)
pic = fields(2)
partnum = fields(3)
(...etc through options)
Loop
' Close the file.
FirmwareStreamReader.Close()
Catch ex As Exception
' File missing.
ResponseDialogResult = MessageBox.Show("File not Found!", "File Not Found",
MessageBoxButtons.OK, MessageBoxIcon.Question)
If ResponseDialogResult = DialogResult.OK Then
' Exit the program.
Me.Close()
End If
End Try
End Sub
Private Sub cbFW_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbFW.SelectedIndexChanged
lblPwrType.Text = pwrtype
lblPic.Text = pic
lblPartNum.Text = parnum
....etc thruogh options
End Sub
This code works, but only sort of. If i select anything from the combo box, it only gives me the information from the very last line of the CSV file - even if its the first entry in the box. I'm pretty sure it's something simple that I'm messing up.. anyone help?
First we read the lines into Firmware objects then we set this List(Of Firmware) as the DataSource of the ComboBox.
Then we handle the SelectedIndexChanged event of the ComboBox which will get the currently selected firmware and loads its data to the TextBox controls.
This is a tested, working example below:
Public Class Firmware
Public Property ModelName As String
Public Property PowerType As String
Public Property Pic As String
Public Property PartNumber As String
Public Property Firmware As String
Public Property Option1 As String
End Class
Public Class MainForm
Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
Dim lines As String() = Nothing
Try
' Read the file in one step
lines = File.ReadAllLines("fwlist.txt")
Catch ex As Exception
Dim dialogResult As DialogResult = MessageBox.Show(Me, "File not found! Would you like to exit program?", "Error reading file", MessageBoxButtons.YesNo, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2)
If dialogResult = DialogResult.Yes Then
Me.Close()
End If
Exit Sub
End Try
Dim firmwares As List(Of Firmware) = New List(Of Firmware)
For Each line As String In lines
Dim rawData As String() = line.Split({","}, StringSplitOptions.None)
' Create Firmware object from each line
Dim firmware As Firmware = New Firmware() With
{
.ModelName = rawData(0),
.PowerType = rawData(1),
.Pic = rawData(2),
.PartNumber = rawData(3),
.Firmware = rawData(4),
.Option1 = rawData(5)
}
' We store the read firmwares into a list
firmwares.Add(firmware)
Next
' Set the list as the data source of the combobox
' DisplayMember indicates which property will be shown in the combobox
With cboModelNames
.DataSource = firmwares
.DisplayMember = "ModelName"
End With
End Sub
Private Sub cboModelNames_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboModelNames.SelectedIndexChanged
RefreshForm()
End Sub
Private Sub RefreshForm()
' Get the selected item as Firmware object
Dim currentFirmware As Firmware = DirectCast(cboModelNames.SelectedItem, Firmware)
' Refresh all the textboxes with the information
With currentFirmware
txtPowerType.Text = .PowerType
txtPic.Text = .Pic
txtPartNumber.Text = .PartNumber
txtFirmware.Text = .Firmware
txtOption1.Text = .Option1
End With
End Sub
End Class
Every time you set the value of a variable like pwrtype, its old value is thrown away and there is no way to get it back. And even if you did save multiple values for each variable, you would need a way to figure out which value goes with the currently selected item in the combo box. To resolve these two issues you need:
a way to group values from the same line together
a way to save all values read from the file, not just the most recent ones
Let's start with the first issue, grouping values together. In the example code below, I created a Structure type called FirmwareInfo to serve that purpose. Each FirmwareInfo has its own pwrtype, pic, etc.
The other piece of the puzzle that you are missing is a way to save more than one Firmware. The easiest way to do this is to add each FirmwareInfo to the combo box's item list, instead of adding just the display string. The combo box will convert each item to a string in the UI; the ToString() method tells it how you want this conversion to be done.
I haven't run this example code so I can't guarantee there aren't mistakes in there, but hopefully it's enough to show the general idea.
Dim filename As String = "fwlist.txt"
Structure FirmwareInfo
Public pwrtype As String
Public pic As String
Public partnum As String
Public FirmwareName As String
Public Overrides Function ToString() As String
Return FirmwareName
End Function
End Structure
Private Sub ReadFirmwaresLoad(sender As Object, e As EventArgs) Handles Me.Load
' Load the items into the NameComboBox list.
Dim ResponseDialogResult As DialogResult
Try
Dim FirmwareStreamReader As StreamReader = New StreamReader(filename)
' Read all the elements into the list.
Do Until FirmwareStreamReader.Peek = -1
Dim lineread = FirmwareStreamReader.ReadLine()
Dim fields As String() = lineread.Split(",")
Dim info As New FirmwareInfo With {
.FirmwareName = fields(0),
.pwrtype = fields(1),
.pic = fields(2),
.partnum = fields(3)
}
cbFW.Items.Add(info)
Loop
' Close the file.
FirmwareStreamReader.Close()
Catch ex As Exception
' File missing.
ResponseDialogResult = MessageBox.Show("File not Found!", "File Not Found",
MessageBoxButtons.OK, MessageBoxIcon.Question)
If ResponseDialogResult = DialogResult.OK Then
' Exit the program.
Me.Close()
End If
End Try
End Sub
Private Sub cbFW_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbFW.SelectedIndexChanged
Dim currentInfo = DirectCast(cbFW.SelectedItem, FirmwareInfo)
lblPwrType.Text = currentInfo.pwrtype
lblPic.Text = currentInfo.pic
lblPartNum.Text = currentInfo.parnum
' ....etc through options
End Sub

Check if form is Opened

I give this question for more knowledge. How can I know if the form is Opened in my application or not, in order not to open it again I mean not to create an instance of the same form while it's running
Dim frmCollection As New FormCollection()
frmCollection = Application.OpenForms()
If frmCollection.Item("Form2").IsHandleCreated Then
MsgBox("Yes Opened")
Else
Dim f As New Form2()
With f
.Text = "form2"
.Show()
End With
End If
if I executes this code many times it will create more instances of the form Form2
How can I check if this form is not already opened
You can try it like this:
Imports System.Linq ' need to add
If Application.OpenForms().OfType(Of Form2).Any Then
MessageBox.Show("Opened")
Else
Dim f2 As New Form2
f2.Text = "form2"
f2.Show()
End If
You can use the following code:
If myForm.IsHandleCreated then
myForm is open
End If
As an extension of the answers given (thank you, all), here's a simple way to activate or show:
Dim frmCollection = System.Windows.Forms.Application.OpenForms
If frmCollection.OfType(Of Form2).Any Then
frmCollection.Item("Form2").Activate()
Else
Dim newForm2 = New Form2
newForm2.Show()
End If
For more simplicity you may create a public static bool variable which will tell whether the form is opened or not. On form load event assign 'true' and on closed event assign 'false' value.
ANOTHER refactoring way from the one initiated by HumbleBeginnings:
Dim xChildWindows = Application.OpenForms.OfType(Of frmForm2)
If xChildWindows.Any Then
xChildWindows.First().Focus() 'Focus if exists
Else
Dim xfrmNew As New frmForm2() 'Open window if doeasn't exists
xfrmNew.MdiParent = Me
xfrmNew.Show()
End If
Hate to be a kill joy but some day some one is going to try and understand your code.
Dim frm as New frmDontknow
Dim frmCollection = System.Windows.Forms.Application.OpenForms
For i As Int16 = 0I To frmCollection.Count - 1I
If frmCollection.Item(i).Name = frm.Name Then
frmCollection.Item(i).Activate()
Exit Sub
End If
Next i
Then do the show etc as required?
Check if form is Opened, To validate if a form is open we use this method and function to be able to invoke from any form and use less code.
Example :
This will use it in a form with mdiContainer and a panel object with 3 buttons that shows the 3 windows form.
Imports System
Imports System.Reflection
Private Sub OpenWindowsForm(ByVal FormName As String)
Dim instForm As Form = Application.OpenForms.OfType(Of Form)().Where(Function(frm) frm.Name = FormName).SingleOrDefault()
If instForm Is Nothing Then
Dim frm As New Form
frm = DirectCast(CreateObjectInstance(FormName), Form)
frm.MdiParent = Me
Me.Panel1.Controls.Add(frm)
Me.Panel1.Tag = frm
frm.Show()
Else
instForm.Select()
instForm.WindowState = FormWindowState.Maximized
instForm.BringToFront()
End If
End Sub
Public Function CreateObjectInstance(ByVal objectName As String) As Object
Dim obj As Object
Try
If objectName.LastIndexOf(".") = -1 Then
objectName = [Assembly].GetEntryAssembly.GetName.Name & "." & objectName
End If
obj = [Assembly].GetEntryAssembly.CreateInstance(objectName)
Catch ex As Exception
obj = Nothing
End Try
Return obj
End Function
How to use in click events
Private Sub btnRegistro_Click(sender As Object, e As EventArgs) Handles btnRegistro.Click
OpenWindowsForm("Registro")
End Sub
Private Sub btnBusqueda_Click(sender As Object, e As EventArgs) Handles btnBusqueda.Click
OpenWindowsForm("Busqueda")
End Sub
Private Sub btnCalendario_Click_1(sender As Object, e As EventArgs) Handles btnCalendario.Click
OpenWindowsForm("Calendario")
End Sub
Here is an image of the Sample code
you can try this
Dim formText As String
Dim prevText As String
Private Sub OpenForm(ByVal frm As Windows.Forms.Form)
formText = frm.Text
If formText = prevText Then Exit Sub
CloseForms()
' Make it a child of this MDI form before showing it.
frm.MdiParent = Me
frm.Show()
frm.Location = New Point(0, 0)
prevText = formText
End Sub
Private Sub CloseForms()
For Each ChildForm As Form In Me.MdiChildren
ChildForm.Close()
Next
End Sub
Private Sub NewToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PayablesToolStripMenuItem.Click
OpenForm(frmPayables)
End Sub
For Each frm As Form In Application.OpenForms
If frm.Name = Form1.Name Then
MessageBox.Show("Opened")
End If
Next