Vb.net DataGridView repeating - vb.net

I have a problem in my DataGridView, please refer to the image below.
Image 1 shows that I've clicked "Add to Cart" on one of my products, the DataGridView shows the product.
Image 1
The problem is when I want to add another product, the list of products in the DataGridView repeats itself instead of adding another different product.
Image 2 shows what happens when I clicked "Add to Cart" on a new product.
Image 2
Private Sub btn_add_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_add.Click
grd_cart.RowCount = grd_cart.RowCount + 1
For i As Integer = 0 To grd_cart.RowCount - 1
Dim product As String = grd_cart(0, i).Value
Dim price As String = grd_cart(1, i).Value
Dim quantity As String = grd_cart(2, i).Value
Dim subtotal As String = grd_cart(3, i).Value
grd_cart(0, i).Value = txt_product_id.Text
grd_cart(1, i).Value = txt_price.Text
grd_cart(2, i).Value = num_quantity.Value
grd_cart(3, i).Value = grd_cart(1, 0).Value * grd_cart(2, 0).Value
Next
End Sub

You don't need to cicle through the grid.
(Of course, this may depend on how you calculate the sub total.)
You just need to add a new Row to the grid, using the current values.
This can be a way to do it.
'Check whether the Price value is a number or not (to be safe)
'If can't be used as a number, return
Dim _Price As Long
If Long.TryParse(txt_price.Text, _Price) = False Then Return
'Calculate the subtotal value based on quantity and unit price
'I know not everyone calculates the sub total this way. In case, just add a comment.
Dim _subtotal As Long = CLng(num_quantity.Value) * _Price
'Add the new Row values
grd_cart.Rows.Add(New String() {txt_product_id.Text,
_Price.ToString,
num_quantity.Value.ToString,
_subtotal.ToString})
This is the result:
You might also present the values in Currency format:
'The output can also be formatted using the local Currency format
grd_cart.Rows.Add(New String() {txt_product_id.Text,
_Price.ToString("C"),
num_quantity.Value.ToString,
_subtotal.ToString("C")})
This is the result:

Related

Printing a different value in a text box on multiple copies

I have a button that prints a form on the current record.
The form contains a combobox with something like: 123005TEST
This combobox is a lookup to another textbox which is a combination of three text boxes(on a different form):
=([OrderNr] & (""+[Aantal]) & "" & [SapArtNr])
OrderNr is 12300 and Aantal is 5 and SapArtNr is TEST, creating: 123005TEST
My question is, when I click print, is it possible to print a certain amount of copies based on Aantal 5, so printing 5 copies.
And here comes the tricky part.
To have each printed copy a different value in the combobox, so the first copy would have this written in the combobox on the printed paper: 123001TEST and copy two would be 123002TEST and so on, until 5.
I didn't understand which textbox will receive the sequential text. So I put a dummy in the example code:
Option Explicit
Private Sub cmdPrintIt_Click()
Dim strOrderNr As String
Dim strAantal As String
Dim strSapArtNr As String
Dim intHowManyCopies As Integer
Dim intCopy As Integer
Dim strToTextBox As String
strOrderNr = Me.OrderNr.Text
strAantal = Me.Aantal.Text
strSapArtNr = Me.SapArtNr.Text
On Error Resume Next
intHowManyCopies = CInt(strAantal)
On Error GoTo 0
If intHowManyCopies <> 0 Then
For intCopy = 1 To intHowManyCopies
strToTextBox = strOrderNr & CStr(intCopy) & strSapArtNr
Me.TheTextBoxToReceiveText.Text = strToTextBox
'put your code to print here
Next
Else
MsgBox "Nothing to print! Check it."
End If
End Sub

Listbox returns index as integer, but I want the current string value

In this case, I want to store in the txtCountryQuery variable the currently selected country with the currentCountry variable name as String, for example, Brazil. But not, the number of the list index, I want to store it but as text, returning the corresponding country. Attached is part of my code.
Code:
'other subroutine
lbCountry.List = regionArray
lbCountry.ListIndex = 0
End Sub
'''Main code:
Private Sub lbCountry_Click()
Dim currentCountry As String
currentCountry = lbCountry.ListIndex
rsRegion.MoveFirst
rsRegion.Move (currentCountry)
txtCountryQuery = currentCountry
End Sub
You will need to cycle through the items in the list box. You grab the actual content, by reading out the columns that are there. Here an example that would add the items to a dictionary object:
For i = 0 To lbCountry.ListCount - 1
If Not dict.Exists(lbCountry.Column(1, i)) Then
dict.Add lbCountry.Column(1, i), i
End If
Next i

How to fix previous item of a variable gets sent instead of the current one

I have a vb.net program that keeps track of people that bought raffle tickets and also keeps track of their phone numbers. When I go to add a new person(via a for loop) it gets the number of tickets they bought and adds that amount of there name and number to an array. But when I click it, it adds one extra of the prevoius name and number I had put in.
I have tried moving the place where the variable assignment takes place.
I tried to null the variable and reassign it.
Button Click
Public Sub BtnAddtckt_Click(sender As Object, e As EventArgs) Handles
BtnAddtckt.Click
Reset()
Dim MNES As String = Nameinput.Text.ToString
Dim NUMES As String = Numinput.Text.ToString
Dim LenPrev = ApplicantsName.Length - 1
Dim LenNext = (LenPrev) + (NumEntries.Value - 1)
ReDim Preserve ApplicantsName(LenNext)
ReDim Preserve ApplicantsNum(LenNext)
For Subs As Integer = LenPrev To LenNext
ApplicantsNum(Subs) = NUMES
ApplicantsName(Subs) = MNES
Next
LbltotalRegistered.Text = (ApplicantsName.Length - 1).ToString
For nme As Integer = 0 To (ApplicantsName.Length - 1)
Form2.LBname.Items.Add(ApplicantsName(nme).ToString)
Next
For nem As Integer = 0 To (ApplicantsNum.Length - 1)
Form2.LBnum.Items.Add(ApplicantsNum(nem).ToString)
Next
End Sub
I expect it to not add an extra person to each aray.

Return associated DataGridView row to it's corresponding Datatable row

Reformatting this question since nobody seemed to understand it. I have a datatable called dtCSV. I am searching through dtCSV for a specific value and I am able to find the row I need ( i dont need help with this part) . dtCSV is also bound to a datagridview. (this is what I need help with) How can I take my row that I found with the search and find it's corresponding row in the datagridview control so that I can highlight that entire row? Thanks
Function GetDebitorsString(ByVal Name As String, ByVal RowName As String) As String
Dim dt As New DataTable
If System.IO.File.Exists("data\debitors\debitors.xml") Then
dt.ReadXml("data\debitors\debitors.xml")
Else
MsgBox("File data\debitors\debitors.xml was not found.", MsgBoxStyle.Information, "Warning")
Return String.Empty
End If
Dim FoundRow() As DataRow = dt.Select("Name='" & Name & "'")
If FoundRow IsNot Nothing Then
Return FoundRow(0).Item(RowName).ToString
Else
Return String.Empty
End If
End Function
Private Sub btnScan_Click(sender As Object, e As EventArgs) Handles btnScan.Click
'looks through all the bills in the CSV and see's if they match with the inputted bills. If they match the cleared date is inputted into the cleared column and the row is turned green in the csv dgv
For Each row In dt.Rows 'loop through each of the bills listed looking for a matching bank statement with the same amount paid
If GetDebitorsString(row("Name").ToString, "Search") IsNot String.Empty Then 'find the search string for the debitor
Dim FoundRow() As DataRow = dtCSV.Select("Description Like '*" & GetDebitorsString(row("Name").ToString, "Search") & "*'") 'try to see if any bank statements match the search string
If FoundRow.Count >= 0 Then
'item was found
If row("Amount Paid").ToString IsNot String.Empty Then 'ignore bills with no amounts typed in
If Convert.ToDouble(row("Amount Paid")) = Convert.ToDouble(FoundRow(0).Item("Debit")) Then 'if the amount listed in the bill matches the amount in the bank statement
row("Cleared") = FoundRow(0).Item("Date").ToString 'set the date it cleared in the cleared cell
End If
End If
End If
End If
Next
If you know the searchKey say Name and the column number of Name in DGV, just use a for loop.
Example:
Dim key = "Andrew"
Dim col_Name = 5
For Each r As DataGridViewRow In dgvCSV.Rows
If r.Cells(col_Name).Value = key Then
Return r.Index
End If
Next

VBA code multiple if condition and put complete datein respective column

I am creating macro and I am stuck in creating the main page of VBA code. we have a sheet named "Renewal" in which all the customer information we dump. Column C we have customer number, Column D We have product type Dental, LIFE & Dis. Column A we have to put complete data, and Column B we have to put annual premium. Now I want the main page where I can one input box1 in which I put customer number, combo box1 in which 3 option I will get "DENTAL, LIFE, DIS., input box2 Date of completion, and input box3 annual premium. If input box1 and combo box1 condition satisfy then date will put on same row of column A and annual premium in column B respectively.
The wording of your question was very interesting, maybe a screenshot might be better. Ok this is what I have crafted. I am sorry I am not sure this code will work 100% as I have not got Word installed on this machine so had to write it in notepad, so may not be the best solution. As suggested in one of the comments - you have to add add() in the button1_click event. Hopefully this has been of some use.
Private Sub add() 'Add the add sub routine to the button1_click
Sheets("Renewal").Activate() 'makes the sheet activate
if textbox1.text <> "" and textbox2.text <> "" and textbox3.text <> "" and combobox1.text <> "" then 'condition
dim pos as integer 'used to find next position
pos = findNext() 'adds next position value
activesheet.cells(1,pos).value = textbox2.text 'adds Date of completion
activesheet.cells(2,pos).value = textbox3.text 'adds annual premium
activesheet.cells(3,pos).value = textbox1.text 'adds customer number
activesheet.cells(4,pos).value = combobox1.text 'adds product type
'unsure if combobox1.text is correct.
end if 'end of the condition
End sub 'end of sub routine
Private function findNext() 'this function finds the next position in sheet
dim x as integer 'used as a counter
x = 1 'counter = 1
do 'start of iteration
x = x + 1 'counting
loop until activesheet.cells(1,x).value = "" 'end when cell (A, counter) has no value
return x 'returns the counter value
End function 'end of function
P.S. If you are a complete begin beginner - This video may help you with the ui: https://www.youtube.com/watch?v=hCIpMwdKCgE