This is what the teacher is asking:
User selects an item from the list
The information about the item displays to the right (description, retail price, units)
The user enters a quantity and clicks Add to Cart
The subtotal, tax and grand total display
User clicks complete purchase button and a confirm order box appears. User clicks OK and the form clears for another transaction.
This is what I done:
Any Suggestions as of why I keep getting this error "Argument Index is not a valid value"
Imports System.IO
Public Class MainForm
Const strFILENAME As String = "Inventory.txt"
Dim dblTaxRate As Double = 8.75
Dim InventoryCollection As New Collection
Public Sub AddRecord(ByVal InvItem As Inventory)
Try
inventoryCollection.Add(InvItem, InvItem.InventoryNumber)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub ClearMainForm()
txtDesc.Text = String.Empty
txtRetail.Text = ""
txtOnHand.Text = ""
txtInvNumber.Text = String.Empty
End Sub
Private Sub UpdateListBox()
lstInventory.Items.Clear()
Dim InvItem As Inventory
For Each InvItem In inventoryCollection
lstInventory.Items.Add(InvItem.InventoryNumber)
Next
If lstInventory.Items.Count > 0 Then
lstInventory.SelectedIndex = 0
Else
ClearMainForm()
End If
End Sub
Private Sub SaveRecord(ByVal objInventory As Inventory)
Dim Writer As StreamWriter
Try
Writer = File.AppendText("Inventory.txt")
Writer.WriteLine(objInventory.InventoryNumber)
Writer.WriteLine(objInventory.Description)
Writer.WriteLine(objInventory.Retail.ToString())
Writer.WriteLine(objInventory.OnHand.ToString())
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim objInventory As New Inventory
Dim inventoryFile As System.IO.StreamReader
Dim blnFound As Boolean = False
Dim inventoryCollection As New Collection
Try
' Open the file.
If System.IO.File.Exists(strFILENAME) Then
End If
inventoryFile = System.IO.File.OpenText(strFILENAME)
'Enter loop and read till end of file.
Do Until inventoryFile.Peek = -1
'Read lines from file, save into Inventory object properties.
objInventory.InventoryNumber = inventoryFile.ReadLine
objInventory.Description = inventoryFile.ReadLine
objInventory.PartCost = inventoryFile.ReadLine
objInventory.Retail = inventoryFile.ReadLine
objInventory.OnHand = inventoryFile.ReadLine
'Display data in text boxes.
lstInventory.Items.Add(objInventory.InventoryNumber)
Loop
'Close the file.
inventoryFile.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub DisplayInput(ByVal InvItem As Inventory)
'Display from Collection to Label boxes
Try
txtDesc.Text = InvItem.Description
txtOnHand.Text = InvItem.OnHand.ToString()
txtRetail.Text = InvItem.Retail.ToString()
txtInvNumber.Text = InvItem.InventoryNumber
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub lstInventory_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstInventory.SelectedIndexChanged
Dim objInventory As Inventory
'See if an Item is Selected
If lstInventory.SelectedIndex <> -1 Then
'Retrieve student's data from inventoryCollection. Convert object into Inventory object.
Try
objInventory = CType(inventoryCollection.Item(lstInventory.SelectedItem), Inventory)
Catch ex As Exception
'Display error message.
MessageBox.Show(ex.Message)
Console.WriteLine("")
End Try
End If
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
'Clear Form
ClearMainForm()
End Sub
Private Sub btnExits_Click(sender As Object, e As EventArgs) Handles btnExits.Click
'Close the Form
Me.Close()
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim InvID As New Inventory
InventoryCollection.Add(InvID, InvID.InventoryNumber)
End Sub
End Class
Public Class Inventory
Private StrinvNumber As String
Private strdesc As String
Private decCost As Decimal
Private decretailPrice As Decimal
Private IntqtyOnHand As Integer
'Constructor
Public Sub New()
StrinvNumber = String.Empty
strdesc = String.Empty
decCost = 0.0
decretailPrice = 0.0
IntqtyOnHand = 0.0
End Sub
Public Property InventoryNumber() As String
Get
Return StrinvNumber
End Get
Set(ByVal value As String)
StrinvNumber = value
End Set
End Property
Public Property Description() As String
Get
Return strdesc
End Get
Set(ByVal value As String)
strdesc = value
End Set
End Property
Public Property PartCost() As Decimal
Get
Return decCost
End Get
Set(ByVal value As Decimal)
decCost = value
End Set
End Property
Public Property Retail() As Decimal
Get
Return decretailPrice
End Get
Set(ByVal value As Decimal)
decretailPrice = value
End Set
End Property
Public Property OnHand() As Integer
Get
Return IntqtyOnHand
End Get
Set(ByVal value As Integer)
IntqtyOnHand = value
End Set
End Property
End Class
Presumably the issue is here:
objInventory = CType(inventoryCollection.Item(lstInventory.SelectedItem), Inventory)
Does lstInventory contain Integer values and are those values valid indexes into inventoryCollection? I would expect not. Are those two lists supposed to correspond to each other? If so then you should be using SelectedIndex rather than SelectedItem. Probably you should have just bound the list to the ListBox in the first place and then the SelectedItem would be the object you needed already.
Related
When I select an element from the combo box, the DGV clears.
There is an Access database that has a table with room booking details, the code is supposed to use the combo box to filter the data to only show the selected room type.
I'm not sure if this code is on the right lines, so any help is appreciated.
Code for the form:
Imports System.Data.OleDb
Public Class frmViewEditBookings
Private DB As New DBControl
Private CurrentRecord As Integer = 0
'Error checking and reporting
Private Function NoErrors(Optional Report As Boolean = False) As Boolean
If Not String.IsNullOrEmpty(DB.Exception) Then
If Report = True Then MsgBox(DB.Exception)
Return False
Else
Return True
End If
End Function
Private Function NotEmpty(text As String) As Boolean
Return Not String.IsNullOrEmpty(text)
End Function
Public Sub RefreshGrid()
'Run query
DB.ExecQuery("SELECT * FROM tblRoomBookings")
'Report and abort on errors
If NoErrors(True) = False Then Exit Sub
'Fill combo box
For Each R As DataRow In DB.DT.Rows
cboRoomType.Items.Add(R("RoomType"))
Next
'If data is returned populate DGV and build update command
If DB.RecordCount > 0 Then
dgvBookings.DataSource = DB.DS.Tables(0)
dgvBookings.Rows(0).Selected = True
End If
End Sub
Private Sub frmViewEditBookings_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown
'Perform subroutine RefreshGrid
RefreshGrid()
'Display specified room
If DB.RecordCount > 0 Then cboRoomType.SelectedIndex = 0
'Disable Save Button
btnSave.Enabled = False
End Sub
Private Sub SearchRoomType(RoomType As String)
'Add parameters and run query
DB.AddParam("#RoomType", RoomType)
DB.ExecQuery("SELECT * FROM tblRoomBookings WHERE RoomType =#RoomType")
'Report and abort on errors
If NotEmpty(DB.Exception) Then MsgBox(DB.Exception) : Exit Sub
'Report and abort on errors
If NoErrors(True) = False OrElse DB.RecordCount < 1 Then Exit Sub
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
'Run subroutine SearchRoomType
SearchRoomType(cboRoomType.Text)
End Sub
Private Sub cboRoomType_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cboRoomType.SelectedIndexChanged
If Not String.IsNullOrEmpty(cboRoomType.Text) Then SearchRoomType(cboRoomType.Text)
'Hide lblSearch
lblSearchRoomType.Visible = False
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
'Close the form
Me.Close()
End Sub
End Class
DBControl class:
Imports System.Data.OleDb
Public Class DBControl
'Create connection to the database
Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=|DataDirectory|\NewHotel.mdb;")
'Prepare the database command
Private DBCmd As OleDbCommand
'Database data
Public DBDA As OleDbDataAdapter
Public DT As DataTable
Public DS As DataSet
'Query parameters
Public Params As New List(Of OleDbParameter)
'Query stats
Public RecordCount As Integer
Public Exception As String
Public Sub ExecQuery(Query As String)
'Reset query stats
RecordCount = 0
Exception = ""
Try
'Open database connection
DBCon.Open()
'Create database command
DBCmd = New OleDbCommand(Query, DBCon)
'Load params into database command
Params.ForEach(Sub(x) DBCmd.Parameters.Add(x))
'Clear params list
Params.Clear()
'Execute command and fill database
DS = New DataSet
DT = New DataTable
DBDA = New OleDbDataAdapter(DBCmd)
RecordCount = DBDA.Fill(DS)
DBCon.Close()
Catch ex As Exception
Exception = ex.Message
End Try
'Close connection to database
If DBCon.State = ConnectionState.Open Then DBCon.Close()
End Sub
'Include query and command parameters
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New OleDbParameter(Name, Value)
Params.Add(NewParam)
End Sub
End Class
Thank you for your time :)
I am attempting to load thousands of URLs into a list, then simultaneously download the webpage source of all of those URLs. I thought I had a clear understanding of how to accomplish this but it seems that the process goes 1 by 1 (which is painstakingly slow).
Is there a way to make this launch all of these URLs at once, or perhaps more than 1 at a time?
Public Partial Class MainForm
Dim ImportList As New ListBox
Dim URLList As String
Dim X1 As Integer
Dim CurIndex As Integer
Public Sub New()
Me.InitializeComponent()
End Sub
Sub MainFormLoad(sender As Object, e As EventArgs)
Try
Dim lines() As String = IO.File.ReadAllLines("C:\URLFile.txt")
ImportList.Items.AddRange(lines)
Catch ex As Exception
MessageBox.Show(ex.ToString)
Finally
label1.Text = "File Loaded"
X1 = ImportList.Items.Count
timer1.Enabled = True
If Not backgroundWorker1.IsBusy Then
backgroundWorker1.RunWorkerAsync()
End If
End Try
End Sub
Sub BackgroundWorker1DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs)
URLList = ""
For Each item As String In ImportList.Items
CheckName(item)
CurIndex = CurIndex + 1
Next
End Sub
Sub BW1_Completed()
timer1.Enabled = False
label1.Text = "Done"
End Sub
Sub CheckName(ByVal CurUrl As String)
Dim RawText As String
Try
RawText = New System.Net.WebClient().DownloadString(CurUrl)
Catch ex As Exception
MessageBox.Show(ex.ToString)
Finally
If RawText.Contains("404") Then
If URLList = "" Then
URLList = CurUrl
Else
URLList = URLList & vbCrLf & CurUrl
End If
End If
End Try
End Sub
Sub Timer1Tick(sender As Object, e As EventArgs)
label1.Text = CurIndex.ToString & " of " & X1.ToString
If Not URLList = "" Then
textBox1.Text = URLList
End If
End Sub
Sub Button1Click(sender As Object, e As EventArgs)
Clipboard.Clear
Clipboard.SetText(URLList)
End Sub
End Class
i have in a windows.form a combobox and a datagridview,
i add rows in datagridview with a button and get the value(string) from combobox and if i double click on the row of datagridview i delete the row.
When i add the row i want to hide/disable/remove the combobox value and when i delete the row i want to restore it in combobox.
The combobox values are binding from dataset source and combobox is dropdownlist style.
I try some things until now but this is what i think is better approach and where i am:
Dim filterList As List(Of String) = New List(Of String)
Private Sub filterListAdd()
Dim dgResult As String
filterList .Clear() 'Clear the list so no duplicates
For i As Integer = 0 To combobox.Items.Count - 1
Dim a As String = combobox.GetItemText(combobox.Items(i))
For row As Integer = 0 To Dgview.RowCount - 1
For col As Integer = 0 To Dgview.ColumnCount - 1
Next
Surname = Dgview.Rows(row).Cells(0).Value.ToString
If dgResult = a Then
filterList .Add(a) 'Add to list
End If
Next
Next i
End Sub
Private Sub Button_Click(sender As Object, e As EventArgs) Handles Button.Click
Dgview.Rows.Add(combobox.Text)
filterListAdd()
'Here i want to bindingsource.filter = filterList
End Sub
Private Sub Dgview_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles Dgview.MouseDoubleClick
Dgview.Rows.Remove(Dgview.CurrentRow)
'I Guess here with the same way i filter it again
End Sub
Any help will be appreciated, thanks in advance.
Panos
Public Class Form1
Dim clsItems As New ArrayList()
Private Sub RemoveComboItem()
Me.BindingSource.Position = Me.BindingSource.Find("1", Combobox.Text)
Dim 1Add As String = DirectCast(BindingSource.Current, DataRowView).Item("1").ToString
Dim 2Add As String = DirectCast(BindingSource.Current, DataRowView).Item("2").ToString
Dim 3Add As String = DirectCast(BindingSource.Current, DataRowView).Item("3").ToString
clsItems.Add(New MyItem(1Add, 2Add, 3Add))
BindingSource.RemoveCurrent()
End Sub
Private Sub AddComboItem(dg As DataGridView) ' Because i have two datagridviews
Dim 1 As String = dg.CurrentRow.Cells(0).Value.ToString()
For i = 0 To clsItems.Count - 1
If i <= clsItems.Count - 1 Then
If 1 = clsItems(i).1 Then
Dim drNewRow As DataRow
drNewRow = DeeDataSet.Tables("Table").NewRow()
drNewRow("1") = clsItems(i).1
drNewRow("2") = clsItems(i).2
drNewRow("3") = clsItems(i).3
DeeDataSet.Tables("Table").Rows.Add(drNewRow)
clsItems.Remove(clsItems(i)) ' Remove it from array so no duplicates
End If
End If
Next
End Sub
Private Sub Button_Click(sender As Object, e As EventArgs) Handles Button.Click
RemoveComboItem()
End Sub
Private Sub Dgview_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles Dgview.MouseDoubleClick
AddComboItem(Dgview)
Dgview.Rows.Remove(Dgview.CurrentRow)
End Sub
End class
Public Class MyItem
Private m_s1 As String
Private m_s2 As String
Private m_s3 As String
Public Sub New(1As String, 2 As String, 3 As String)
M_sName = 1
M_sSurname = 2
M_sTitle = 3
End Sub
Public ReadOnly Property 1
Get
Return m_s1
End Get
End Property
Public ReadOnly Property 2
Get
Return M_s2
End Get
End Property
Public ReadOnly Property 3
Get
Return M_s3
End Get
End Property
End Class
In that form i don't update the dataset because every change i want to make it in other form, so when i finish from here the dataset.table has no changes.
When the form loads there is a combo box where you select a GL account. Once one is selected, then I click the Get Vendor button to load the vendor information. I'm having problems with the code mainly on the form.vb. I need to populate the listview box with the vendor information and I'm not sure what I did wrong. I have referenced the payables class library etc. Getting error at vendor.count on form.vb. I haven't input the database info on Payables.DB b/c I'm not sure what it yes. Thanks.
Public Class Vendor
Dim m_VendorName As Integer
Dim m_FirstName As String
Dim m_LastName As String
Dim m_City As String
Dim m_State As String
Public Sub New()
End Sub
Public Property VendorName() As String
Get
Return m_VendorName
End Get
Set(ByVal value As String)
m_VendorName = value
End Set
End Property
Public Property FirstName() As String
Get
Return m_FirstName
End Get
Set(ByVal value As String)
m_FirstName = value
End Set
End Property
Public Property LastName() As String
Get
Return m_LastName
End Get
Set(ByVal value As String)
m_FirstName = value
End Set
End Property
Public Property State() As String
Get
Return m_State
End Get
Set(value As String)
m_State = value
End Set
End Property
Public Property City() As String
Get
Return m_City
End Get
Set(value As String)
m_City = value
End Set
End Property
End Class
Imports System.Data.SqlClient
Public Class VendorDB
Public Shared Function GetVendors() As List(Of Vendor)
Dim vendorList As New List(Of Vendor)
Dim connection As SqlConnection = PayablesDB.GetConnection
Dim selectStatement As String =
"SELECT VendorName, FirstName, Last Name, State, City " &
"FROM Vendor " &
"ORDER BY Description"
Dim selectCommand As New SqlCommand(selectStatement, connection)
Try
connection.Open()
Dim reader As SqlDataReader = selectCommand.ExecuteReader()
Dim vendor As Vendor
Do While reader.Read
vendor = New Vendor
vendor.VendorName = (reader("VendorName")).ToString
vendor.FirstName = reader("Firstname").ToString
vendor.LastName = (reader("LastName")).ToString
vendor.State = (reader("State")).ToString
vendor.City = (reader("City")).ToString
vendorList.Add(vendor)
Loop
reader.Close()
Catch ex As SqlException
Throw ex
Finally
connection.Close()
End Try
Return vendorList
End Function
End Class
Public Class GLAccount
Private m_Description As String
Public Sub New()
End Sub
Public Property Description() As String
Get
Return m_Description
End Get
Set(ByVal value As String)
m_Description = value
End Set
End Property
Imports System.Data.SqlClient
Public Class GLAccountDB
Public Shared Function GetGLAccountList() As List(Of GLAccount)
Dim accountList As New List(Of GLAccount)
Dim connection As SqlConnection = PayablesDB.GetConnection
Dim selectStatement As String =
"SELECT Description " &
"FROM GLAccounts " &
"ORDER BY Description"
Dim selectCommand As New SqlCommand(selectStatement, connection)
Try
connection.Open()
Dim reader As SqlDataReader = selectCommand.ExecuteReader()
Dim account As GLAccount
Do While reader.Read
account = New GLAccount
account.Description = reader("Description").ToString
accountList.Add(account)
Loop
reader.Close()
Catch ex As SqlException
Throw ex
Finally
connection.Close()
End Try
Return accountList
End Function
End Class
Now this is what I have referred to the payables(form and validator class)
Public Class Validator
Public Shared Function IsPresent(control As Control) As Boolean
Dim comboBox As ComboBox = CType(control, ComboBox)
If comboBox.SelectedIndex = -1 Then
MessageBox.Show(comboBox.Tag.ToString & " is a required field.")
comboBox.Select()
Return False
Else
Return True
End If
End Function
End Class
Payables
Public Class Form1
Dim vendorList As List(Of Vendor)
Dim accountList As List(Of GLAccount)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LoadComboBoxes()
End Sub
Private Sub LoadComboBoxes()
accountList = GLAccountDB.GetGLAccountList
cboAccounts.DataSource = accountList
cboAccounts.DisplayMember = "Description"
End Sub
Private Sub btnGetVendors_Click(sender As Object, e As EventArgs) Handles btnGetVendors.Click
Dim vendorList As List(Of Vendor)
Try
If Vendor.Count > 0 Then
vendorList = VendorDB.GetVendors()
Else
MessageBox.Show("All invoices were paid in full")
End If
Catch ex As Exception
End Try
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
End Class
Have trouble connecting exception to textbox input - Program should only accept "IL", "MO" or "WI" - But it's accepting every input. Everything I tried I'm hitting a brick wall - I know the solution is there, I just need some help. Thanks
Form Codes
Public Class Form1
Dim packages(4) As Packages
Dim pkg As Integer = 0
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
packages(0) = New Packages("Z111", "Eau Claire", "WI")
packages(1) = New Packages("Z121", "Vicki Vale", "IL")
packages(2) = New Packages("Z131", "Sammy Davis", "MO")
packages(3) = New Packages("Z141", "Jon Smith", "IL")
packages(4) = New Packages("Z151", "Suzie Cassidy", "WI")
DisplayInfo()
End Sub
Sub DisplayInfo()
txtID.Text = packages(pkg).PackageID
txtCity.Text = packages(pkg).DestinationCity
txtState.Text = packages(pkg).DestinationState
lblPackageCount.Text = "Package # " & pkg + 1
End Sub
Private Sub btnFirst_Click(sender As Object, e As EventArgs) Handles btnFirst.Click
pkg = 0
DisplayInfo()
End Sub
Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
If pkg > 0 Then
pkg -= 1
DisplayInfo()
End If
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If pkg < packages.Length - 1 Then
pkg += 1
DisplayInfo()
End If
End Sub
Private Sub btnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click
pkg = packages.Length - 1
DisplayInfo()
End Sub
Private Sub btnSaveChanges_Click(sender As Object, e As EventArgs) Handles btnSaveChanges.Click
Try
packages(pkg).PackageID = txtID.Text
packages(pkg).DestinationCity = txtCity.Text
packages(pkg).DestinationState = txtState.Text
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End Class
Class Codes
Public Class Packages
Private packID As String
Private desCity As String
Private desState As String
Sub New(id As String, city As String, state As String)
packID = id
desCity = city
desState = state
End Sub
Public Property PackageID As String
Get
Return packID
End Get
Set(value As String)
packID = value
End Set
End Property
Public Property DestinationCity As String
Get
Return desCity
End Get
Set(value As String)
desCity = value
End Set
End Property
Public Property DestinationState As String
Get
Return desState
End Get
Set(value As String)
If desState = "IL" Then
desState = value
ElseIf desState = "WI" Then
desState = value
ElseIf desState = "MO" Then
desState = value
Else
Throw New Exception("Can not deliver to this state")
End If
End Set
End Property
End Class
Your immediate problem is you're checking the property value instead of the passed value. Something like this should work:
Set(value As String)
'This creates a temporary string array of available states and checks if _
the value passed is contained in the array
If {"IL","WI", "MO"}.Contains(value)Then
desState = value
Else
Throw New Exception("Can not deliver to this state")
End If
End Set
If this is something you may need to change you could make the array a property.