VB.Net and Access - Getting Totaliser Value - vb.net

I'm trying to databind a textbox to a totaliser value in an access database. I currently update the database via OleDbCommand and then edit any existing entries via databinding on the form.
I have everything working fine, but I want a textbox to show the totaliser (sum) of a particular column in the datbase. Access shows this totaliser underneath the column if the database is opened.
Is there a method to bind this value to the textbox?
Thanks

Well, however you are accessing the database, you need to make a call to get the SUM of your desired table.
If we are talking about SQL, it would look something like:
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = " SELECT SUM(total) AS Total From YourTable"
cmd.CommandText = sSQL
OleDbDataReader dr = cmd.ExecuteReader()
If dr.Read() Then
set total = Convert.ToInt32(dr["Total"])
End If
You could load this into a DataTable/DataSet or use the DataReader and assign the result (the sum) to a textbox, like:
TextBox1.Text = total
If you are using Linq it could look like (this is just an example):
Dim yourObject = From cust In db.Customers
Group By cust.City
Into Average(cust.Orders.Count)
Order By Average
DataGridView1.DataSource = yourObject

Related

Naming Column Header Based On Results From Database

net and would to have the Header Text of columns in a datagridview be named after results from the database, e.g the query in my code returns four dates,30/08/2017,04/09/2017,21/09/2017 and 03/02/2018. My aim is to have the column headers in the data grid named after those dates. Your help will highly be appreciated.
sql = "SELECT COUNT (ServiceDate) As NoOfServiceDates FROM (SELECT DISTINCT ServiceDate FROM tblattendance)"
Using command = New OleDbCommand(sql, connection)
Using reader = command.ExecuteReader
reader.Read()
ColumnNo = CInt(reader("NoOfServiceDates")).ToString
End Using
End Using
DataGridView1.ColumnCount = ColumnNo
For i = 0 To DataGridView1.Columns.Count - 1
sql = "SELECT DISTINCT ServiceDate FROM tblattendance"
Using command = New OleDbCommand(sql, connection)
Using reader = command.ExecuteReader
While reader.Read
DataGridView1.Columns(i).HeaderText = reader("ServiceDate").ToString
End While
End Using
End Using
Next
The current code re-runs the query each time through the column count loop, meaning it will set the column header for that column to all of the date values in sequence, so the last value in the query shows in the all the columns. You only need to run the query once:
Dim i As Integer = 0
sql = "SELECT DISTINCT ServiceDate FROM tblattendance"
Using command As New OleDbCommand(sql, connection), _
reader As OleDbDatareader = command.ExecuteReader()
While reader.Read
DataGridView1.Columns(i).HeaderText = reader("ServiceDate").ToString
i+= 1
End While
End Using
Additionally, this still results in two separate trips to the database, where you go once to get the count and again to get the values. Not only is this very bad for performance, it leaves you open to a bug where another user changes your data from one query to the next.
There are several ways you can get this down to one trip to the database: loading the results into memory via a List or DataTable, changing the SQL to include the count and the values together, or adding a new column each time through the list. Here's an example using the last option:
DataGridView1.Columns.Clear()
Dim sql As String = "SELECT DISTINCT ServiceDate FROM tblattendance"
Using connection As New OleDbConnection("string here"), _
command As New OleDbCommand(sql, connection)
connection.Open()
Using reader As OleDbDataReader = command.ExecuteReader()
While reader.Read
Dim column As String = reader("ServiceDate").ToString()
DataGridView1.Columns.Add(column, column)
End While
End Using
End Using
Even better if you can use something like Sql Server's PIVOT keyword in combination with the DataGridView's AutoGenerateColumns feature for DataBinding, where you will write ONE SQL statement that has both column info and data, and simply bind the result set to the grid.
The For Next is incorrect. You execute your command for every column, when you only need to execute it once. The last result from the DataReader will be the header for every column as currently written.
You should iterate through your DataReader and increment the cursor variable there:
Dim i As Integer = 0
Using command = New OleDbCommand(sql, connection)
Using reader = command.ExecuteReader
While reader.Read
DataGridView1.Columns(i).HeaderText = reader("ServiceDate").ToString
i += 1
End While
End Using
End Using

Filter databound combobox based on value in another column from the same dataset

I am attempting to create a process scheduler as a project in school this summer and am quite new to using VB. Currently I have a combobox bound to the "EmployeeBindingSource" which holds information for every single employee in a company. Each employee is assigned a skill level for each work station in the building. What I would like to do is if an employee is listed as having "0" skill in say, the assembly station, when selecting an employee to assign to the assembly station, that particular employee will not appear in the combobox.
From doing some research I believe that rather than binding the combobox to the data source in the designer, I will have to assign values to the each combo box in the code on a form load.
This is the access table that holds all the employee information
In the table we can see that Steve has a skill level of "0" in the AS_Level category (assembly).
However, here we can see that he still appears as an option for the assembly area when creating a new project
Currently all the data binding happens in the designer for each combo box and therefore no code has been written for the data binding. At the moment each combo box is bound to the "Full_Name" column in the access table.
Again, I am quite new to VB so I apologize if this is too vague. Let me know if I can give any more helpful information. Thank you all in advance.
After adding the code suggested here is what I have
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
datafile = "C:\Users\Jacob\Desktop\Halton\HaltonProject.accdb"
connString = provider & datafile
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "SELECT * FROM [Employee] WHERE (SP_Level <> '" & 0 & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
Dim dr As OleDbDataReader = cmd.ExecuteReader
Dim userfound As Boolean = False
Dim Full_Name As String
While dr.Read
userfound = True
Full_Name = dr("Full_Name").ToString
SP_Emp1.Items.Add(Full_Name)
SP_Emp2.Items.Add(Full_Name)
SP_Emp3.Items.Add(Full_Name)
SP_Emp4.Items.Add(Full_Name)
End While
myConnection.Close()
Works completely now!
Based on your comments and post, I assume, the checkboxes on the left enable/disable the comboboxes on that row, and since you're binding them individually if you change your query so it looks like this:
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [Employee] WHERE AS_Level <> 0 , myConnection) Dim dr As OleDbDataReader = cmd.ExecuteReader
Note that the where clause will vary depending on your needs, so it could be WHERE AS_Level <> 0 or WHERE SP_Level <> 0 and so on.
I have never used an Ole database so I'm not quite sure about the syntax, hope this helps.

Query for sum of column values not giving me a value

I have a GridView in my ASP Page where the user can change one of the values and the other is a read only value. I want that when the row is updated a query will execute that sums the value of one column to the other and changes it. Ex... Value1 + Value 2 = Value2. I wrote this in the code-behind:
Protected Sub GridView1_RowUpdated(sender As Object, e As EventArgs) Handles GridView1.RowUpdated
Dim connectionString As String = "mystring"
Using cn As New SqlConnection(connectionString)
Dim cmd As New SqlCommand()
cmd = New SqlCommand("Select (Purchased + Actual) as Actual from Product", cn)
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
End Using
yet the value doesn't sum. A part of me says I need an update command to save the value or something like that but what I read in W3 and other places doesn't point me to that. I guess since there's different products (of course) I need a WHERE ProductID = #Parameter... right? Still that code should change the rest of the values and it doesn't. Any pointers or anything that flew over me? Thanks a bunch!
Looks like you want
Update Product Set Value2 = Value1 + Value2
Where ProductId = #Parameter

Get last UserID from SqlServer to textbox control

I have a table customers where each cust has UserID as "A000" now I need to get the last entered ID from the database and display it in my textbox.
Can anyone suggest me how do I do this?
As I have seen many articles describing about
SELECT ##IDENTITY
SELECT SCOPE_IDENTITY()
SELECT IDENT_CURRENT('TableName')
but unable to know where to use it correctly.
And here is how I'm doing it :
Dim strConnection As String = "Data Source=.\SqlExpress;Initial Catalog=Subscription;Integrated Security=True"
'Establish SQL Connection
Dim con As New SqlConnection(strConnection)
'Open database connection to connect to SQL Server
con.Open()
'Data table is used to bind the resultant data
Dim dtusers As New DataTable()
'Create a new data adapter based on the specified query.
Dim da As New SqlDataAdapter("SELECT MAX(UserID) FROM Customers", con)
Dim cmd As New SqlCommandBuilder(da)
da.Fill(dtusers)
con.Close()
Use ExecuteScalar :
Dim comm as new SqlCommand
comm.CommandText = "SELECT MAX(UserID) FROM Customers"
comm.Connection = con
Dim MaxUserID as object = comm.ExecuteScalar()
Use the ExecuteScalar method to retrieve a single value (for example,
an aggregate value) from a database
Side Note : ExecuteScalar() may return a null reference (Nothing in VB.NET) if the result of the command is empty like when there are no records in the table or there is condition that doesn't produce any records. Make sure you check that before assigning the value to your TextBox.

unable to find specified column in result set index out of bounds index out of range exception

i am having trouble putting a value in a textbox. Each time a ticket is sold i put the total price in a textbox, each time a ticket is sold for the same concert it increases by adding its self to the total price. It works at the first sale, but after that it breaks down. here is the code and thanks in advance.
Private Function DisplayMoneyTaken() As Integer
Dim totalMoney As Integer
'open the database connection
strSQL = "SELECT MAX(Total_Money) FROM Sales WHERE Concert_Id =" + Mid(cboVenue.Text, 1, 4)
conn.Open()
cmd.Connection = conn
cmd.CommandText = strSQL
cmd.CommandType = CommandType.Text
dr = cmd.ExecuteReader()
'read the record returned
dr.Read()
If IsDBNull(dr.Item(0)) Then
totalMoney = txtPrice.Text
Else
DisplayMoneyTaken = dr.Item("Total_Money") + Val(txtPrice.Text)
End If
'close the database
conn.Close()
Return totalMoney
End Function
It doesn't appear that your query has a column named "Total_Money". You didn't name the single column your query returns.
Michael,
When using an aggregate function, it is necessary to also assign an alias to that column.
For example
strSQL = "SELECT MAX(Total_Money) as CaChing FROM Sales WHERE Concert_Id =" + Mid(cboVenue.Text, 1, 4)
If you do not assign an alias, the server will sometimes assign one. But you have to know or guess what it will be. Its a lot better to just pick one that makes sense.
You can also index items with a number, this is what you did when you were checking for NULLs.
This same syntax could have been used when accessing the value.
DisplayMoneyTaken = dr.Item(0) + Val(txtPrice.Text)