Code to track the no of data already entered - vb.net

I have a form where i want to enter Sr. Nos for machines.it have a combo box where i have to choose the invoice no saved in another table along with its corresponding qty of machines.
When i am entering machine details it should say me as "enter Sr no. for X'th/Y'th machine where y is the total qty saved in db and x is the no. of sr no. i have saved+1 "
It should also allow me to save the no. some where.. i mean in any variable so that if i pause my work in between and after word if continue it should say me "enter detail for X'th/Y'th" not "1'st/Y'th"
I am using this code:
Private Sub get_qty()
Dim qtySql As String = "SELECT * FROM invoice1 where chalan_no='" & cmbChal_no.Text & "'"
cnnOLEDB.Open()
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(qtySql, cnnOLEDB)
Dim dr As OleDb.OleDbDataReader = cmd.ExecuteReader
If dr.Read = True Then
qnty = dr("qty")
End If
cnnOLEDB.Close()
End Sub
Private Sub Srno_enter()
Dim noSql As String = "SELECT count(sr_no) FROM Vendor_machine GROUP BY(chalan_no) having chalan_no='" & cmbChal_no.Text & "'"
cnnOLEDB.Open()
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(noSql, cnnOLEDB)
' Suggest code retrieve count(sr_no) <--------------------------
cnnOLEDB.Close()
End Sub
private sub show()
lblMachine= 'Result of count(sr_no)' "/" qnty
end sub
Please suggest me the code for same.. thank you..

Just use an Identity column in your database and let the database engine do the work of creating the next free number.
If you wrote a stored procedure to do the insert, you could return the serial number as an output parameter

Related

Visual basic - Incrementing the score

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim READER As MySqlDataReader
Dim Query As String
Dim connection As MySqlConnection
Dim COMMAND As MySqlCommand
Dim item As Object
Try
item = InputBox("What is the item?", "InputBox Test", "Type the item here.")
If item = "shoe" Then
Dim connStr As String = ""
Dim connection As New MySqlConnection(connStr)
connection.Open()
Query = "select * from table where username= '" & Login.txtusername.Text & " '"
COMMAND = New MySqlCommand(Query, connection)
READER = COMMAND.ExecuteReader
If (READER.Read() = True) Then
Query = "UPDATE table set noOfItems = noOfItems+1, week1 = 'found' where username= '" & Login.txtusername.Text & "'"
Dim noOfItems As Integer
Dim username As String
noOfItems = READER("noOfItems") + 1
username = READER("username")
MessageBox.Show(username & "- The number of items you now have is: " & noOfGeocaches)
End If
Else
MsgBox("Unlucky, Incorrect item. Please see hints. Your score still remains the same")
End If
Catch ex As Exception
MessageBox.Show("Error")
End Try
I finally got the message box to display! but now my code does not increment in the database, can anybody help me please :D
Thanks in advance
After fixing your typos (space after the login textbox and name of the field retrieved) you are still missing to execute the sql text that updates the database.
Your code could be simplified understanding that an UPDATE query has no effect if the WHERE condition doesn't find anything to update. Moreover keeping an MySqlDataReader open while you try to execute a MySqlCommand will trigger an error in MySql NET connector. (Not possible to use a connection in use by a datareader). We could try to execute both statements in a single call to ExecuteReader separating each command with a semicolon and, of course, using a parameter and not a string concatenation
' Prepare the string for both commands to execute
Query = "UPDATE table set noOfItems = noOfItems+1, " & _
"week1 = 'found' where username= #name; " & _
"SELECT noOfItems FROM table WHERE username = #name"
' You already know the username, don't you?
Dim username = Login.txtusername.Text
' Create the connection and the command inside a using block to
' facilitate closing and disposing of these objects.. exceptions included
Using connection = New MySqlConnection(connStr)
Using COMMAND = New MySqlCommand(Query, connection)
connection.Open()
' Set the parameter value required by both commands.
COMMAND.Parameters.Add("#name", MySqlDbType.VarChar).Value = username
' Again create the reader in a using block
Using READER = COMMAND.ExecuteReader
If READER.Read() Then
Dim noOfItems As Integer
noOfItems = READER("noOfItems")
MessageBox.Show(username & "- The number of items you now have is: " & noOfItems )
End If
End Using
End Using
End Using

VB.net Query wont retrieve data from access database

I have created a query using vb.net with parameters which should allow the query to retrieve data from my access database but however when I click on the button it only shows blank fields but no rows are retrieved from the database. Could you please help me what I am currently doing wrong.
Imports System.Data.OleDb
Public Class RouteToCruise
Private Sub RouteToCruise_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Route_Btn_Click(sender As Object, e As EventArgs) Handles Route_Btn.Click
Try
Dim row As String
Dim connectString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\DeepBlueTables.mdb"
Dim cn As OleDbConnection = New OleDbConnection(connectString)
cn.Open()
Dim CruiseQuery As String = "SELECT Route.RouteName + ', ' + Cruise.CruiseID As CruiseRoute FROM Route INNER JOIN Cruise ON Route.RouteID = Cruise.RouteID WHERE CruiseID = ?"
Dim cmd As New OleDbCommand(CruiseQuery, cn)
'cmd.Parameters.AddWithValue("CruiseID", OleDbType.Numeric).Value = Route_Txt.Text
cmd.Parameters.AddWithValue(("CruiseID"), OleDbType.Numeric)
Dim reader As OleDbDataReader = cmd.ExecuteReader
'RCTable.Width = Unit.Percentage(90.0)
RCTable.ColumnCount = 2
RCTable.Rows.Add()
RCTable.Columns(0).Name = "CruiseID"
RCTable.Columns(1).Name = "RouteName"
While reader.Read
Dim rID As String = reader("RouteID").ToString()
cmd.Parameters.AddWithValue("?", rID)
row = reader("CruiseID") & "," & ("RouteName")
RCTable.Rows.Add(row)
End While
reader.Close()
cn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
If the user enters route name in the text box then the rows should show cruise ID and route name for each of the selected routes. for example if users enters Asia in the text box, clicks on the button then the query should return the cruiseID for the cruises which are going to Asia.
Your use of parameters makes no sense. First you call AddWithValue and provide no value, then you execute the query and then you start adding more parameters as you read the data. Either you call AddWithValue and provide a value, or you call Add and then set the Value on the parameter object created. Either way, it MUST be before you execute the query or it's useless.
myCommand.Parameters.AddWithValue("#ParameterName", parameterValue)
or
Dim myParameter = myCommand.Parameters.Add("#ParameterName", OleDbType.Numeric)
myParameter.Value = parameterValue

Adding data from Text boxes directly to database and viewing updated gridview

still very new to this and can't seem to find exactly what I'm looking for. Quick run-through on what I'm trying to accomplish. I have a datagridview (3 columns - Id, Name, Address) that is connected to a local .mdf database file, that I'm able to search through using a search textbox. My goal NOW is to submit records into the database directly using 2 text fields and the Id field to automatically increment. (Id++, txtName.Text, txtAddress.Text) and to use a send button(btnSend) to activate this event.(PLEASE KEEP IN MIND, MY GOAL IS TO HAVE EVERYONE INCLUDING THE NEW RECORD SHOW UP IN THE DATAGRIDVIEW AND FOR THE NEW ROW TO BE INSERTED DIRECTLY TO THE DATABASE AND SAVE ANY CHANGES) I've been hammering at this for a couple days now and would appreciate any help. Below is my code, but please keep in mind I'm still new and trying to figure this language out so if there's any unnecessary code, please do let me know... Also if you want to help with one additional thing, maybe some code on how to export that table to a different file from an export button. Thanks! I'm currently also getting an error saying "Cannot find table 0." when I click the btnSend button.
Public Sub btnSend_Click(ByVal sender As Object, e As EventArgs) Handles btnSend.Click
Try
Dim connectionString As String
Dim connection As SqlConnection
Dim ds As New DataSet("Table")
Dim dataset As New DataSet()
Dim sqlInsert As String
Dim sqlSelect As String
Dim Id As Integer = 5
Dim newRow As DataRow = dataset.Tables(0).NewRow()
connectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=""" & My.Application.Info.DirectoryPath & "\Database1.mdf"";Integrated Security=True;"
sqlInsert = "INSERT INTO Table (#Id, #Name, #Address) VALUES (" & Id & ", '" & txtName.Text & "','" & txtAddress.Text & "')"
sqlSelect = "SELECT * FROM Table"
connection = New SqlConnection(connectionString)
Dim da As New SqlDataAdapter()
connection.Open()
da.Fill(ds)
Using da
da.SelectCommand = New SqlCommand(sqlSelect)
da.InsertCommand = New SqlCommand(sqlInsert)
da.InsertCommand.Parameters.Add(New SqlParameter("Id", SqlDbType.Int, 4, Id))
da.InsertCommand.Parameters.Add(New SqlParameter("Name", SqlDbType.NText, 50, txtName.Text))
da.InsertCommand.Parameters.Add(New SqlParameter("Address", SqlDbType.NText, 50, txtAddress.Text))
Using dataset
da.Fill(dataset)
newRow("Id") = Id
newRow("Name") = txtName.Text
newRow("Address") = txtAddress.Text
dataset.Tables(0).Rows.Add(newRow)
da.Update(dataset)
End Using
Using newDataSet As New DataSet()
da.Fill(newDataSet)
End Using
End Using
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
Throw New Exception("Problem loading persons")
End Try
Dim updatedRowCount As String = gvDataViewer.RowCount - 1
lblRowCount.Text = "[Total Row Count: " & updatedRowCount & "]"
End Sub

I cant retrieve picture from access database

I would like to retrieve the picture from access database when the user login to the system.
Firstly, the user will type his/her Staff ID and Password to login.
Secondly, if the user granted to login the system, it will show another form.
Thirdly, that another form will show the user's first name and last name.
Furthermore, I would like to show the picture that saved in Access Database too. Could any senior help me?
This is my code:
Private Sub ShowStaffData(ByVal CurrentRow)
txtFirstName.Text = DTS.Tables("Staff").Rows(CurrentRow)("User's_First_Name")
txtLastName.Text = DTS.Tables("Staff").Rows(CurrentRow)("User's_Last_Name")
End Sub
Private Sub RetrieveStaffInformation()
Dim StaffID As String
Dim i, j As Integer
Dim Command As New OleDbCommand("SELECT Picture FROM Staff WHERE Staff_ID ='" & txtStaff_ID.Text & "'", Connection)
Command.Parameters.AddWithValue("#Staff_ID", txtStaff_ID.Text)
Connection.Open()
Dim PictureData As Byte() = DirectCast(Command.ExecuteScalar(), Byte())
Connection.Close()
Command.Dispose()
Dim Stream As New IO.MemoryStream(PictureData)
picStaff.Image = Image.FromStream(Stream)
txtStaff_ID.Text = Login.txtStaff_ID.Text
Stream.Dispose()
StaffID = txtStaff_ID.Text
j = DTS.Tables("Staff").Rows.Count - 1
i = 0
While i <> j + 1
If StaffID = DTS.Tables("Staff").Rows(i)("Staff_ID") Then
ShowStaffData(i)
End If
i += 1
End While
End Sub
Check you OleDbCommand. Maybe your select statement is not findind the Staff_ID because your where clause is comparing Staff_ID against a string, and in most cases this ID is a numeric value stored as integer.
Dim Command As New OleDbCommand("SELECT Picture FROM Staff WHERE Staff_ID = ?", Connection)
Command.Parameters.AddWithValue("#Staff_ID", CInt(txtStaff_ID.Text))
Anyway, you should provide some error details, if you got any errors...

VB.NET & SQL, pasting SELECT query results to a textbox

I'm building a client database system for a travel company.
They want to be able to retrieve all of their customer emails with one click, and have it appear on a textbox on the page, where they can copy it off and paste it into Outlook.
Currently, the textbox is called emailList, and is invisible until the button called emailGet is clicked.
However, I have no idea how to make the text appear into the textbox from an SQL query.
My SQL query is: SELECT CEmail FROM Clients. That's pretty much it.
In pseudocode, what I'm trying to do is:
sqlQuery = "SELECT CEmail FROM Clients"
Execute select query and store results (in a variable? or maybe directly to the textbox?)
emailList.Text = Result of sqlQuery
Thank you! :)
Private Sub GetEmailAddresses()
Dim sText As String = String.Empty
Dim sConnString As String = String.Empty 'Put your connection string in here
Using cn As New OleDb.OleDbConnection(sConnString)
cn.Open()
Dim cmd As New OleDb.OleDbCommand("SELECT CEmail FROM Clients", cn)
Dim r As OleDb.OleDbDataReader = cmd.ExecuteReader()
If Not r.HasRows Then Exit Sub
Do While r.Read()
sText = sText & ";" & r.GetString(0)
Loop
cn.Close()
End Using
txtboxList.Text = sText
End Sub