Vb.net SQL SUM value to a label - vb.net

I have a table by name assetcategory in database.I need the sum of quantity attribute where Asset_name attribute equal to CPU. After this i want to store the result in a label.
I wrote the following query but its not working.
Dim cmd3 As New OleDbCommand("Select sum(Quantity) from assetcategory where ID ='A013' and Asset_Name='CPU'", con)
Dim dr1 As OleDbDataReader
dr1 = cmd3.ExecuteReader
While dr1.Read
Label4.text=dr1.item(0).Tostring
End While

This would happen if sum(Quantity) is NULL because no rows match

Related

UPDATE SET SUM IN SQL FROM ANOTHER TABLE IN VB.NET

I want to update the set sum but my code is not perfect, maybe I need to add or modify the sql.
I tried "UpdateTABLE2()" but the result is not yet in accordance with the output result I want
thanks
TABLE1
INVNO QTY PRICE DIS
1000 10 10000 10
1000 20 20000 20
1001 15 10000 10
1001 30 20000 20
TABLE2
INVNO TOTAL
1000
1001
OUTPUT
TABLE2
INVNO TOTAL
1000 410000 QTY*PRICE*(1-DIS/100) for total from INVNO 1000
1001 615000 QTY*PRICE*(1-DIS/100) for total from INVNO 1001
Private Sub fillDataGrid()
Try
Dim query As String = "SELECT INVNO,SUM((QTY*PRICE)*(1-DIS/100)) AS TOTAL FROM TABLE1 GROUP BY INVNO"
Using con As OleDbConnection = New OleDbConnection(cn)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
'cmd.Parameters.AddWithValue("#CODE", ComboBox1.SelectedValue)
Using da As New OleDbDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
da.Fill(dt)
da.Dispose()
source3.DataSource = dt
Me.DataGridView3.DataSource = source3
Me.DataGridView3.Refresh()
End Using
End Using
End Using
Catch ex As Exception
End Try
End Sub
Sub UpdateTABLE2()
Try
Dim sql As String = "UPDATE TABLE2 INNER JOIN TABLE1 ON TABLE1.[INVNO] = TABLE2.[INVNO] SET TABLE2.[TOTAL] = [QTY]*[PRICE]*(1-[DIS]/100)"
Using conn As New OleDbConnection(cn),
cmd As New OleDbCommand(sql, conn)
'cmd.Parameters.AddWithValue("#INVNO", ComboBox1.SelectedValue)
conn.Open()
cmd.ExecuteNonQuery()
End Using
There are 3 problems to solve:
Calculate the total for each row in TABLE1. You could add a calculated field directly to the table, create a view that does it for you or do it with an inline WITH expression. I propose a view:
CREATE VIEW V_TABLE1
AS
SELECT *, (CAST(QTY AS MONEY) * CAST(Price AS MONEY) * (CAST(1 AS MONEY) - (CAST(DIS AS MONEY) / CAST(100 AS MONEY)))) AS Total FROM Table_1;
Group the data. Again, could be just a query or a view, here again as a view:
CREATE VIEW V_TABLE1_Consolidated
AS
SELECT NO, SUM(Total) AS Total FROM V_TABLE1
GROUP BY NO
Fill that into a table. Challenge yourself first whether it really needs to be serialized, and if that is a requirement, you could use something like the following code: (Watch out: It temporarily drops everything of TABLE2)
TRUNCATE TABLE TABLE2;
INSERT INTO TABLE2 SELECT * FROM V_TABLE1_Consolidated;
If you have additional data that you have omitted like an order number or a customer or a time range and the updates should only be refreshed for that order/customer/time range then you have to replace the TRUNCATE TABLE by a DELETE FROM TABLE2 WHERE ....

count the specific record from access in vb.net

So i am making a voting program but i am stuck right now.
I have searched for solutions and i have followed them precisely but still no result.
Basically i want to count the total occurrence for each specific record from access in visual basic.
For example i have the candidate number 1 voted by three persons and candidate 2 by 7 persons, i want to show this voting result in a textbox but somehow it always shows me the wrong number
So here is my code:
Dim TotalVotes As Integer
myCommand = New OleDbCommand("SELECT CandidateNumber, COUNT (*) FROM Student_Voting GROUP BY CandidateNumber", dbconn)
TotalVotes = myCommand.ExecuteScalar
NovTextBox.Text = TotalVotes
myCommand.Dispose()
myReader.Close()
This query here gives a result of the first candidate number not the total votes for selected candidate number:
SELECT CandidateNumber, COUNT (*) FROM Student_Voting GROUP BY CandidateNumber
I have tried this too but still wrong result:
SELECT COUNT(CandidateNumber) AS NoVotes FROM Student_Voting GROUP BY CandidateNumber
I don't know what's the problem here, it's suppose to be simple but yet.
If anyone could help i'd very much appreciate it.
Thanks in advance
First of all, the initial query you're running would return more than one record if you had more than one candidate. ExecuteScaler returns only the first column of the first row.
The question is, do you want all of the records or do you just want one person's record? If you just want one person's record you'll need add a WHERE clause to your sql statement to specify on that candidate.
If you want all of the records it would look something like this:
Using myCommand = New OleDbCommand("SELECT CandidateNumber, COUNT (*) AS CountValue FROM Student_Voting GROUP BY CandidateNumber", dbconn)
Using dr = myCommand.ExecuteReader
' Loops over all the canidate counts one by one.
While dr.Read
Dim totalVotes As Integer = CInt(dr("CountValue"))
Dim candidateNumber As String = dr("CandidateNumber")
End While
End Using
End Using
If you want only one record then you can use ExecuteScaler something like this:
Using myCommand = New OleDbCommand("SELECT COUNT (*) AS CountValue FROM Student_Voting WHERE CandidateNumber = #CandidateNumber GROUP BY CandidateNumber", dbconn)
myCommand.Parameters.Add("#CandidateNumber", OleDbType.VarChar).Value = "1"
Dim totalVotes = CInt(myCommand.ExecuteScalar)
End Using
I don't know the actual types in your database so you would need to tweak the OleDbType to fit your table setup and perhaps some of the casts.

how can I show only the new rows in the datagridview

how can I show only the rows in the gridview,
where primarykey>= primarykey.max - 20 (the 20 latest lines)
When I create a SQL Statement,
can I use a variable which is declared at vb.net?(for example a counter which counts the amount of added rows)
where must I put that statement in?
Use this SQL statement as DataSource
SELECT TOP 20 FROM YourTable ORDER BY PrimaryKey DESC
UPDATE
If table name and PKEY must be dynamic you can use a parameterized command. Once the sql statement is formed you can fill a DataSet and use it as data source when populating the DataGridView
Dim cmd As New SqlCommand("SELECT TOP 20 FROM ? ORDER BY ? DESC", Connection)
cmd.Parameters.AddWithValue("#Table", YourDinamicTableName)
cmd.Parameters.AddWithValue("#PKey", YourDinamicKeyName)
Dim ds As New DataSet
Dim Adapter As New SqlDataAdapter(cmd)
Adapter.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)

Querying 2 tables using dataset in Visual basic

I need help with my visual basic project. I have a Store.accdb database
which has 2 tables, customers and orders. I would like to be able to enter a customer's name (or part of a name) in a textbox and then display the name/s in a DataGridView when the search button is clicked. And then On a separate DataGridView I'd like to display the orders of the selected customer from my first DataGridView when the user clicks the Display button.
Edit: This is what the 2 tables look like
Customers table = custNum, custName, custAddress, custPhone
Orders table = orderNum, orderItem, custNum, price, qty
con.ConnectionString = dbProvider & dbSource
Try
con.Open()
sql = "SELECT custName FROM tblCustomers WHERE custName LIKE '%" & tbSearch.Text.ToUpper & "%'"
ds = New DataSet
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "CustomerDataset")
gridCustomers.DataSource = ds
gridCustomers.DataMember = "CustomerDataSet"
con.Close()
Catch ex As Exception
MessageBox.Show("Could not establish a connection", "Database Error")
End Try
This code works fine, it populates my customers datagridview. I get multiple rows whenever I only enter part of a customer's name. If I enter 'sm' in the textbox, it would display all customers with 'sm' in their name. How can I display the selected customer's (from 1st datagridview) orders in my 2nd datagridview when i click the display button? I hope I am making sense, english is not my first language so please bear with me.
Thanks!
You have to play with many events.
when selecting a customer from datagridview you have to use datagridview's selectedIndexChange event(assuming you have button to select in datagridview)
You have to use the same procedure in datagridview's selectedIndexChange event
con.ConnectionString = dbProvider & dbSource
Try
con.Open()
sql = "SELECT * FROM tblorders WHERE custName ='" & gridSelectedValue & "'"
//Assuming you have custName column in order table
ds = New DataSet
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "OrderDataset")
gridCustomers.DataSource = ds
gridCustomers.DataMember = "OrderDataset"
con.Close()
Catch ex As Exception
MessageBox.Show(ex.message)
End Try
Edit
If you dont have custName in order Then you should have CustNum in your query of DataGridView.
Step 1 - change the query that works. Instead of selecting just the customer name, select the customer id, or whatever the primary key of that table is.
Step 2 - when displaying your data, add an anchor tag with a query string that links to a new page showing the orders. The html should look like something like this:
Fred
In orders.aspx, call a query that brings back all the orders for customer_id = 1.
Oh, yes, by the way, convert all form and url variables to parameters before sending them to your database.
Actually, you only need to define a "Foreign Key" between the two tables, you can see this article to know how:
www.codeproject.com/Articles/28273/Xml-Database-Demo
Read the "Adding the DataTable Relation" section.
If you had made your db with Access, you have to the same thing. The same thing if you're using SQL.

crystal report and sql commands

I have a problem in showing data content from joined table in crystal report my sql query is good and it shown my own data but i when fill crystal report datasource and show it the crystal repeat duplicate and more data my code is:
Dim rep As CrystalReport1 = New CrystalReport1()
Dim objcon = New SqlConnection("data source=(local);initial catalog=hesabres;user id='sa';password='Maysam7026'")
Dim objcom = New SqlCommand
Dim objdata As New DataTable
Dim objdr As SqlDataReader
objcom.CommandText = " SELECT customer.customer_name, customer.customer_tel, orders.order_stuff_name, orders.order_number" & _ " FROM hesabres.dbo.orders orders inner JOIN hesabres.dbo.customer customer ON orders.order_customer_id=customer.customer_id"
objcom.Connection = objcon
objcon.Open()
objdr = objcom.ExecuteReader
objdata.Load(objdr)
rep.SetDataSource(objdata)
CrystalReportViewer1.ReportSource = rep
in fact may bought one chair and ball and jahan bought one ball!
Crystal reports does not show any data itself.
If your database query result is fine then their is something with their code.
I will suggest that please review your code in detail.
Apply distinct keyword in select statement as below and then check it
SELECT Distinct customer.customer_name, customer.customer_tel,
orders.order_stuff_name, orders.order_number" & _ "
FROM hesabres.dbo.orders orders
inner JOIN hesabres.dbo.customer customer
ON orders.order_customer_id=customer.customer_id