How to sum specific data grid view cell with criteria? - vb.net

I created a DataGridView where I am retrieving data by search customer id. I want to sum values in TextBox when I select some specific CheckBox-es of DataGridView.
But the problem is that it is adding all values in all cells of all rows but it should be like that for example; if Column number is 2, then pending value should be shown once in TextBox not after sum both duplicated received cell, and if Column numbers are different like Column number 1 and Column number 2 and both are selected, sum value should be there in TextBox which is named received from data grid view received cell.
I am attaching image and code also what I am trying to do. can someone guide how to do this?
Private Sub Getvalue()
For Each row As DataGridViewRow In DataGridView1.Rows
If DataGridView1.RowCount > 0 Then
Dim isSelected As Boolean = Convert.ToBoolean(row.Cells(0).Value)
If isSelected Then
Dim pending As String = 0
Dim received As String = 0
Dim final amount As String = 0
For index As Integer = 0 To DataGridView1.RowCount - 1
pending += Convert.ToDouble (DataGridView1.Rows(index).Cells(15).Value)
received += Convert.ToDouble(DataGridView1.Rows(index).Cells(14).Value)
finalamount += Convert.ToDouble(DataGridView1.Rows(index).Cells(12).Value)
Next
Label19.Reset Text()
Label19.Text = pending
Label20.Reset Text()
Label20.Text = received
Label24.Reset Text()
Label24.Text = final amount
If Label19.Text <= 0 Then
Label18.Text = ""
Else
Label18.Text = Val(Label 24.Text - Label 19.Text)
End If
End If
End If
Next
End Sub

First, turn on Option Strict as per my comment.
If there are not rows, your For Each row won't run so there is no need to check the RowCount.
Don't declare your accumulation variables inside the loop. They will be a new variable on each iteration. Your inner loop loops through all rows so, of course, you get the sum of all. Eliminate the inner loop.
I have no idea what Reset Text() is. A method can't have a space in its name. Anyway, it you are adding a new value it isn't necessary to clear the old one. If you do need to clear then set to "". Don't update your labels until after the loop. It is useless to update the user interface on each iteration. It will go by too fast for the user to see and it slows down the code.
In general, you need to do arithmetic or numeric comparisons with numeric types and set .Text properties with String type. The Val method has bee replace with several .net methods. .Parse, .TryParse, Convert. and in vb the CInt, CDec, etc.
Private Sub Getvalue()
Dim pending As Double = 0
Dim received As Double = 0
Dim finalAmount As Double = 0
For Each row As DataGridViewRow In DataGridView1.Rows
Dim isSelected As Boolean = CBool(row.Cells(0).Value)
If isSelected Then
pending += CDbl(row.Cells(15).Value)
received += CDbl(row.Cells(14).Value)
finalAmount += CDbl(row.Cells(12).Value)
End If
Next
Label19.Text = pending.ToString
Label20.Text = received.ToString
Label24.Text = finalAmount.ToString
If pending <= 0 Then
Label18.Text = ""
Else
Label18.Text = (finalAmount - pending).ToString
End If
End Sub
EDIT
Normally you would have a purchase. The purchase would have a table in the database with fields like purchase number, date, customer, etc. You would have another table with purchase details. The details table would have fields like details number (primary key), a foreign key purchase number which must match an entry in the purchase table, an item ID and a price.
When a customer wants to return an item or items from a purchase. You would enter the purchase number and fill your grid from the purchase details table.
Select * From PurchaseDetails Where purchaseNumber = #purchaseNumber
Put the check mark by each item returned and sum up the price column.
Purchase Table
PurchaseID | CustomerID | Date
Purchase Details Table
DetailID | PurchaseID | ItemCode | ItemPrice

Related

Insert a value into a row in datagrid vb.net

I'm currently stuck on inserting a value into a row in datagridview in vb.net
My code is:
Dim subtotal As Integer = Val(adult.Text) * 500 + Val(child.Text) * 300
For Each row As DataGridViewRow In DataGridView2.Rows
row.Cells.Insert(subtotal)
Next
It supposed to be like this.
enter image description here
Hint I wanna do it like this
You don't insert a new cell. You get an existing cell in the appropriate column and set its Value property. This line:
row.Cells.Insert(subtotal)
would be like this:
row.Cells(columnIndex).Value = subtotal
That said, that will put the same value in every row. That's probably not what you want but it's all we can you based on the information you've provided. If what you actually expect is to get a different value for each row based on data in that row then the calculation would have to be inside the loop as well, e.g.
Dim adultCount = CInt(row.Cells(adultColumnIndex).Value)
Dim childCount = CInt(row.Cells(childColumnIndex).Value)
Dim subtotal = adultCount * 500 + childCount * 300
row.Cells(subtotalColumnIndex).Value = subtotal
Of course, if you had bound this grid to a DataTable then you could set the Expression property of the DataColumn for the subtotal and it would be calculated automatically.

Find and sum value of a datagridview column in vb.net

I want to find and sum qty value of searched id in data grid view column am using this code
Dim tqty As Double
For Each row As DataGridViewRow In dgv.Rows
If row.Cells.Item(0).Value = cmbItemCode.Text Then
tqty += row.Cells.Item(4).Value
Textbox1.text=tqty
Exit For
End If
Next
The problem is that Textbox1 shows only one top searched row value. For example
id item name qty
1 abc 4
2 xyz 10
1 abc 10
Textbox1 shows the Result only 4.
As soon as you hit the first value, you exit the for statement. Therefore you never get pass the first value. Erase the Exit For it should work.
If DataGridView2.RowCount > 1 Then
Dim tqty As Integer = 0
'if you have the other column to get the result you could add a new one like these above
For index As Integer = 0 To DataGridView2.RowCount - 1
amount += Convert.ToInt32(DataGridView2.Rows(index).Cells(2).Value)
'if you have the other column to get the result you could add a new one like these above (just change Cells(2) to the one you added)
Next
TextBox1.Text = tqty

Use an InputBox to enter prices of 4 items

I'm new to VB. Today I'm working on entering 4 prices for items to purchase using an input box. I need to create a counter in a loop. The only 2 buttons on the form "Enter Prices" and "Exit". So far this is the code I have (see below). I know something is off. When I run it, I'm allowed to enter 4 numbers. But at the end, when the message box comes up to show my total, it just gives me my last number I entered. I know I've got to change a few things, as I need my numbers to be in currency. Any suggestions as to where I need to go from here to get this up and running?
Private Sub btnPrices_Click(sender As Object, e As EventArgs) Handles btnPrices.Click
'Declare a variable as counter and accumulator
Dim intcount As Integer = 1I
Dim intAccumulator As Integer = 0I
'Declare and intialize variable
Dim strInput As String = ""
'Number of Items
Const intNUM_PRICES As Integer = 4
'Pre-test loop will keep iterating as long as the expression is ture.
Do While intcount <= intNUM_PRICES
'Get price of each item purchased
strInput = InputBox("Enter Price " & intcount, "Price Needed")
'Add 1 to the counter
intcount += 1
Loop
'Look at the value placed in the
MessageBox.Show("Your combined Price for all 4 items is: " & strInput)
End Sub
You've only got one variable for the input and each time you call InputBox you replace the previous value each time. If you want a total then you have to add the values, so you need to add the current input to the previous total each time, not replace it. Make sure that you convert the input to a number and use a numeric variable, because adding strings will actually join them, not add them mathematically.

VIsual Basic - Scan same item

How to check if textbox contains the same barcode of the previous item scaned so that if it does, i will automatically increase quantity something like this:
Dim nextItemBarcode As String = Me.txtBarkodi.Text
Dim quantity As Integer = 1
If Me.txtBarkodi.Text = nextItemBarcode Then
quantity += 1
Else
quantity = 1
End If
Do you think I am missing sth or could there be a better algorithm for this scenario?
You're missing something. :-)
You need to store the value of the last bar code, not the next bar code. If the new one is the same as the last, you increment the quantity. If it's not the same, you reset quantity to one and store the new bar code as the last bar code.
Dim lastItemBarcode As String = ""
Dim quantity As Integer
' Scan now. If this is the first bar code,
' quantity will be set to 1 in the Else branch below
' Your scan should work in a loop starting here, so
' it keeps going and doesn't reset lastItemBarcode
' or quantity
If Me.txtBarkodi.Text = lastItemBarcode Then
' bar code same as last. Just increase quantity
quantity += 1
Else
' Either the first item scanned, or a different
' item. Save this bar code as the current one,
' and start our queantity at 1
lastItemBarcode = me.txtBarkodi.Text
quantity = 1
End If

how to count specific word in a listview column

I have a form which is 1 list view and a text box.
* list view has a total of 100 rows of data
* list view has 5 columns
* column 3 has only two possible words yes or no
I want to count the number of occurrence of the word yes in column 3
the total row can be count with this code:
''''''''''COUNT TOTAL ADMISSION''''''''''''''
Dim rowcount As Integer = 0
For Each item As ListViewItem In LVfeestatementBA_I.Items
rowcount = CInt(item.SubItems(0).Text) 'Considering every column always have some value
Next
txttotaladBA_I.Text = rowcount.ToString()
any help will be greatfull
EDIT 1
This is a school assignment. As I said my aim is to find out the number of occurrence of a word in column 3. I have database of MS access which is connected with code and provides the data for the list view. The list view has 5 columns and there are a total of 100 rows. The data in col-3 contains only three words gen, occ, and cc. Now in want to count col-3 for the words with code and show the number like (68) in textbox1
EDIT 2
I applied the function provided by thedarkspoon, but it's not showing the result. I just want the result to be shown in textbox1, ex. if total number of words are 78 then at the time of form_load it should show 78 in textbox1. I solved the problem by adding at last textbox1.text = numofyes and change variable from integer to string now its working
I did not quite understand your scenario (you have to be more clear).
Anyway, given a ListView that displays items that each have 3 subitems and we know that the third subitem will have values of either "yes" or "no" we can build a query like (using linq):
var collectionOfListViewItems = listView1.Items.Cast<ListViewItem>();
var numberOfrowsWithTheThirdSubItemTextEqualToYes = (from c in collectionOfListViewItems where c.SubItems[3].Text == "yes" select c).Count();
Without linq you could do a foreach:
var numberOfrowsWithTheThirdSubItemTextEqualToYes = 0;
foreach (ListViewItem item in listView1.Items)
{
if (item.SubItems[3].Text == "yes")
numberOfrowsWithTheThirdSubItemTextEqualToYes++;
}
Ok here you go, I made this a function but you could easily adapt this to a subroutine:
Function countyes()
'Set up a variable to count the number of yes:
Dim numofyes As Integer = 0
'Count the number of yes (Replace listview1 with the name of your listview):
For Each item As ListViewItem In ListView1.Items
'If the Yes/No is in column 3, you are looking in subitem 2:
If item.SubItems(2).Text = "Yes" Then
'Increment the variable by one if the value is yes:
numofyes = numofyes + 1
End If
Next
'Return our total number of Yes that we found:
Return numofyes
End Function
Hope this helps!