how to make a report act like a bill - vb6

i have a form it's purpose to view a client (client table) and a number of orders (order table)
i need when the user build the order to a client the user can press a button called print bill so the report shows out and the name of client appear in the head section from the client table, and the order in the body section(it could be a 100 item ordered), and the total discount in the footer section
i know the query "Select * from order where id = '"& Txtid.Text &"'"
but i cant do it, it only require a pure sql command without Txtid.Text
So how to include the Txtid.text within the query?
how can i send a whatever query and the result came out in a report, i only can make a command and build a report on it, so it must be a way to change the command from the code so the report view the data dynamiclly

Probably you need to select multiple items.
Try adding a ListBox to your form with multiple selection enabled. You could then concatenate all of your IDs from the ListBox into a string and use the IN comparator for your criteria, like so:
sqlString =
"SELECT " & _
"field1, " & _
"field2, " & _
"fieldn " & _
"FROM " & _
"order " & _
"WHERE " & _
"ID IN (" & concatListIds & ") "

Related

Linking a report to a subform

I have a main report (Projects Overview) which I am trying to create an OnClick event which will take me from the report to the field where that piece of information is entered on a form (LiveJobs).
My problem is that there is a subform (Estimate Items Subform) where the order items are entered. Then there is a subform on that (Production Subform) which is where the components that make up the 'Item' are entered. So a 'Desk' is ordered under 'Items' and then the components of the desk - drawer boxes, top, privacy panel are all entered on the Production Subform so they can all be tracked and monitored for production. As they are being produced there is time scheduled for each of these items in a time slot corresponding to a particular week.
In the report I want to be able to click on the time scheduled for any component and link back to the form and the corresponding week where it is scheduled and move hours around within the order form. My code will currently take me to the correct job but it wont get me to the correct 'layer' of the first subform and then to the correct layer of the component. Lets say for example the 3rd item in an order and then the 2 component of that Item.
Below is my code as it sits currently which only goes as far as trying to get to the correct item on the first subform. I figured if I could figure that out I could use the same logic to get to the correct component. This code results in a "Runtime Error '13' Type Mismatch"...I have been going round and round with this for days... Thanks in advance for any and all help.
Private Sub Estimated_hours_for_current_week_Click()
Dim strWhere As String
Dim DocName As String
DocName = "LiveJobs"
strWhere = "[Job Number]=" & "'" & Me![Job Number] & "'"
DoCmd.OpenForm DocName, acNormal, , strWhere
Forms![LiveJobs].[Estimate Items Subform].SetFocus
'find the Item in the item subform
Dim dbs As DAO.Database
Dim RstItem As DAO.Recordset
Dim strItemCriteria As Integer
Set dbs = CurrentDb
Set RstItem = dbs.OpenRecordset("Estimate Items Subform table", dbOpenDynaset)
strItemCriteria = "[Estimate Item subform table ID] = '" & Me.Estimate_Item_subform_table_ID & "'"
With RstItem
RstItem.MoveLast
DoEvents
RstItem.FindFirst strItemCriteria
Debug.Print (strItemCriteria)
If .NoMatch Then
MsgBox "No Match Found"
End If
End With
Set rs = Nothing
End Sub
I figured out the code. Here it is for reference.
Private Sub Estimated_hours_for_current_week_Click()
Dim frm1 As Form
Dim frm2 As Form
Dim rst1 As DAO.Recordset
Dim rst2 As DAO.Recordset
DoCmd.OpenForm "LiveJobs", _
WhereCondition:="[Job Number]=" & "'" & Me![Job Number] & "'"
Set frm1 = Forms!LiveJobs.Estimate_Items_Subform.Form
Set frm2 = Forms!LiveJobs.Estimate_Items_Subform!ProductionComponentSubform.Form
Set rst1 = frm1.Recordset.Clone
Set rst2 = frm2.Recordset.Clone
With rst1
.FindFirst "[Estimate Item subform table ID] =" & Me.Estimate_Item_subform_table_ID
If .NoMatch Then
MsgBox "Item not found"
Else
frm1.Bookmark = rst1.Bookmark
End If
End With
With rst2
.FindFirst "[Estimate details ID]=" & Me.Estimate_details_ID
If .NoMatch Then
MsgBox "project not found"
Else
frm2.Bookmark = rst2.Bookmark
Forms![LiveJobs].SetFocus
Forms![LiveJobs]![Estimate Items Subform].SetFocus
Forms![LiveJobs]![Estimate Items Subform]![ProductionComponentSubform].Form![Estimated
hours for current week].SetFocus
End If
End With
End Sub

LINQ to SQL, Visual Basic - Listbox Receives the Query NOT the Result

Overview
This is a homework assignment using LINQ to SQL in a Visual Basic application. It is correct in most ways except that I have a partially broken result. Rather than adding the result of my second query to my listbox, my code adds a weird representation of the query itself. Below is a description of the DB, followed by my output (intended and actual), and finally my code. Please point me toward the broken concept so I can figure out what I am missing. Thanks much.
DB info
I am using two tables, called Members and Payments, from one DB. Members has a primary key called ID and also has the fields first_name and last_name. Payments has a foreign key called Members_Id, which is associated to the Member's primary key; Payments also has the payment values under the column Payments.
Output should be like this
Member name = John Smith
$48.00, 10/20/2005
$44.00, 3/11/2006
But is this instead
Member name = SELECT ([t0].[First_Name] + #p1) + [t0].[Last_Name]
AS [value]FROM[dbo].[Members] AS [t0].[ID] = #p0
$48.00, 10/20/2005
$44.00, 3/11/2006
My VB Code
Public Class FormPaymentsGroup
Private db As New KarateClassesDataContext
Private Sub FormPaymentsGroup_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Me.PaymentsTableAdapter.Fill(Me.KarateDataSet.Payments)
'Group payments by Member_ID (FKey) in the Payments table. (Working fine)
Dim IdQuery = From aMember In db.Payments
Group aMember By aMember.Member_Id
Into MemberPayments = Group
For Each memberID In IdQuery
' Use the passed member_Id to target the row in the Members table and return the first_name & last_name.
' PROBLEM: This only seems to be returning the query itself; not the result.
Dim currMemberID = memberID.Member_Id
Dim nameQuery = From aName In db.Members
Where aName.ID = currMemberID
Select aName.First_Name + " " + aName.Last_Name
Dim currName = nameQuery.ToString ' Load the query result into a portable variable.
LbxMemberPayments.Items.Add("Member name = " & currName) ' PROBLEM: This is where the name SHOULD BE posted to the listbox.
' This is bound to the Members table but directs it based on the above IdQuery.
For Each enteredPayment In memberID.MemberPayments
LbxMemberPayments.Items.Add(vbTab & FormatCurrency(enteredPayment.Amount) & ", " & enteredPayment.Payment_Date)
Next
LbxMemberPayments.Items.Add(vbCr) ' Carriage return formatting
Next
End Sub
End Class
change
Dim currName = nameQuery.ToString
to
Dim currName = nameQuery.FirstOrDefault

VBA : Querying Access with Excel on server

I'm working with Excel project wich helps to calculate the price of any peace of furniture. The first task is to pick all the materials from the database.
This is the code:
Sub Material_search()
Dim cnt As New ADODB.connection
Dim rst As New ADODB.Recordset
Dim rcArray As Variant
Dim sSQL As String
Dim db_path As String, db_conn As String
Dim item As String
item = Replace(TextBox1.Text, " ", "%") ' Search word
sSQL = "Select Data, NomNr, Preke, Matas, Kaina, Tiek from VazPirkPrekes " & _
"Where VazPirkPrekes.PirkVazID IN (SELECT VazPirkimo.PirkVazID FROM VazPirkimo Where VazPirkimo.Sandelys like '%ALIAVOS')" & _
" and Year(VazPirkPrekes.Data)>=2011 and Preke Like '%" + item + "%' and Kaina > 0" & _
" Order by Preke, Data Desc"
db_path = Sheets("TMP").Range("B6").value
db_conn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & db_path & ";"
cnt.Open db_conn
rst.Open sSQL, cnt, adOpenForwardOnly, adLockReadOnly
ListBox1.Clear
If Not rst.EOF Then
rcArray = (rst.GetRows)
rcArray = WorksheetFunction.Transpose(rcArray)
Dim a As Variant
With ListBox1
.ColumnCount = 6
.list = rcArray
.ListIndex = -1
End With
End If
rst.Close: Set rst = Nothing
cnt.Close: Set cnt = Nothing
Label4.Caption = UBound(ListBox1.list) + 1
End Sub
recently I came up with some trouble while querying Access mdb file. The problem is when database file is on local disk, the search works very fast, but when i put database file on server, the search takes 10 times longer, which is not acceptable.
Is there any optimisation for this code ? or is it a server problem
Thanks in advance
That query requires Access' database engine retrieve all 190K rows from both tables. It's not surprising it is slow, and the slowness is compounded when the db engine must retrieve 2 * 190K rows across the network.
If TextBox1.Text contains "foo", this is the statement you're asking the db engine to run:
Select Data, NomNr, Preke, Matas, Kaina, Tiek
from VazPirkPrekes
Where
VazPirkPrekes.PirkVazID IN (
SELECT VazPirkimo.PirkVazID
FROM VazPirkimo
Where VazPirkimo.Sandelys like '%ALIAVOS')
and Year(VazPirkPrekes.Data)>=2011
and Preke Like '%foo%'
and Kaina > 0
Order by Preke, Data Desc
The engine must retrieve all 190K rows from the VazPirkimo table before it can determine which of them include Sandelys values which end with "ALIAVOS". If your selection criterion was for values which start with "ALIAVOS", the engine could use an index on Sandelys to limit the number of rows it must retrieve from VazPirkimo. However, since that approach is probably not an option for you, consider adding a numeric field, Sandelys_group, to VazPirkimo and create an index on Sandelys_group. Give all rows where Sandelys ends with "ALIAVOS" the same Sandelys_group number (1). Then your "IN ()" condition could be this:
SELECT VazPirkimo.PirkVazID
FROM VazPirkimo
Where VazPirkimo.Sandelys_group = 1
The index on Sandelys_group will allow the db engine to retrieve only the matching rows, which will hopefully be a small subset of the 190K rows in the table.
There are other changes you can make to speed up your query. Look at this criterion from your WHERE clause:
Year(VazPirkPrekes.Data)>=2011
That forces the db engine to retrieve all 190K rows from VazPirkPrekes before it can determine which of them are from 2011. With an index on Data, this should be much faster:
VazPirkPrekes.Data >= #2011-01-01# AND VazPirkPrekes.Data < #2012-01-01#
This WHERE criterion will be faster with an index on Kaina:
Kaina > 0
Your ORDER BY begs for indexes on Preke and Data.
Order by Preke, Data Desc
Any or all of those changes could help speed up the query, though I don't know by how much. The killer is this WHERE criterion:
Preke Like '%foo%'
The issue here is similar to the problem with the "Sandelys like" comparison. Since this asks for the rows where Preke contains "foo", rather than starts with "foo", the db engine can't take advantage of an index on Preke to retrieve only the matching rows. It must retrieve all 190K VazPirkPrekes rows to figure out which match. Unless you can use a different criterion for this one, you will be limited as to how much you can speed up the query.
Thanks for the optimization tips, but as I said the problem occurs only when I put data base file on server. And there is not much help from optimization. But I thought about other idea.
The search of empty blank "" returns about 40k records (these records covers everything I need) . So I'm going to put all these records on a distinct sheet on workbook_activate event and later do the query only in that sheet.
Sub Database_upload()
Application.DisplayAlerts = False
On Error Resume Next
Sheets("DATA_BASE").Delete
On Error GoTo 0
Application.DisplayAlerts = False
Sheets.Add
ActiveSheet.name = "DATA_BASE"
Sheets("DATA_BASE").Visible = False: Sheets("DARBALAUKIS").activate
Dim cnt As New ADODB.connection
Dim rcArray As Variant
Dim sSQL As String
Dim db_path As String, db_conn As String
Dim item As String
Dim qQt As QueryTable
item = "" 'search for empty blanks
sSQL = "Select Data, NomNr, Preke, Matas, Kaina, Tiek from VazPirkPrekes " & _
"Where VazPirkPrekes.PirkVazID IN (SELECT VazPirkimo.PirkVazID FROM VazPirkimo Where VazPirkimo.Sandelys like '%ALIAVOS')" & _
" and Year(VazPirkPrekes.Data)>=2011 and Preke Like '%" + item + "%' and Kaina > 0" & _
" Order by Preke, Data Desc"
db_path = Sheets("TMP").Range("B6").value
db_conn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & db_path & ";"
db_conn = "ODBC;DSN=MS Access 97 Database;"
db_conn = db_conn & "DBQ=" & db_path
Set qQt = Sheets("Sheet1").QueryTables.Add(connection:=db_conn, Destination:=Sheets("Sheet1").Range("A1"), Sql:=sSQL)
qQt.Refresh BackgroundQuery:=False
End Sub
Results:
Program takes longer on startup, but the search time is acceptable - for me the problem is solved :)

visual basic Combo1.AddItem rs4("holding") wont work why

Merged with ms access database search does not work as intended.
the table name is water and it has two field fname and serial. in the field fname suppose a value 'bill' has 3 serial 1,2 and 3. now i need when i type bill in textbox1 and click search button, the combobox1 should show the serials of 'bill' are 1,2 and 3 .
. m using ms access as db .m using the code but it not working.
is there any other coding to solve this ?
Set rs4 = cn.Execute("select fname, serial from water where fname = '" & Text1.Text & "'")
rs4.MoveFirst
Do While Not rs4.EOF
Combo1.AddItem rs4("serial")
rs4.MoveNext
Loop

Linq Compiled Queries and int[] as parameter

I'm using the following LINQ to SQL compiled query.
private static Func<MyDataContext, int[], int> MainSearchQuery =
CompiledQuery.Compile((MyDataContext db, int[] online ) =>
(from u in db.Users where online.Contains(u.username)
select u));
I know it is not possible to use sequence input paramter for a compiled query and im getting “Parameters cannot be sequences” error when running it.
On another post here related , I saw that there is some solution but I couldn't understand it.
Does anyone know to use complied query with array as input paramter?
Please post example if you do.
Like the post that you referenced, it's not really possible out of the box. The post also references creating your own query provider, but it's a bit of overhead and complexity that you probably don't need.
You have a few options here:
Don't use a compiled query. Rather, have a method which will create a where clause from each item in the array resulting in something like this (psuedo-code):
where
online[0] == u.username ||
online[1] == u.username ||
...
online[n] == u.username
Note that you would have to use expression here to create each OR clause.
If you are using SQL Server 2008, create a scalar valued function which will take a table-valued parameter and a value to compare againt. It will return a bit (to indicate if the item is in the values in the table). Then expose that function through LINQ-to-SQL on your data context. From there, you should be able to create a CompiledQuery for that. Note that in this case, you should take an IEnumerable<string> (assuming username is of type string) instead of an array, just because you might have more than one way of representing a sequence of strings, and to SQL server for this operation, it won't matter what the order is.
One solution that I have found myself doing (for MS SQL 2005/2008). And I'm not sure if it is appropriate in all scenarios is to just write dynamic sql and execute it against the datacontext using the ExecuteQuery method.
For example, if I have an unbounded list that I am trying to pass to a query to do a contains...
' Mock a list of values
Dim ids as New List(of Integer)
ids.Add(1)
ids.Add(2)
' ....
ids.Add(1234)
Dim indivs = (From c In context.Individuals _
Where ids.Contains(c.Id) _
Select c).ToList
I would modify this query to create a SQL string to execute against the database directly like so...
Dim str As New Text.StringBuilder("")
Dim declareStmt as string = "declare #ids table (indivId int) " & vbcrlf)
For i As Integer = 0 To ids.Count - 1
str.Append("select " & ids(i).ToString() & " & vbcrlf)
If i < ids.Count Then
str.Append("union " & vbcrlf)
End If
Next
Dim selStatement As String = "select * From " & context.Mapping.GetTable(GetType(Individuals)).TableName & _
" indiv " & vbcrlf & _
" inner join #ids ids on indiv.id = ids.id"
Dim query = declareStmt & str.ToString & selStatement
Dim result = context.ExecuteQuery(of Individual)(query).ToList
So barring any syntax errors or bugs that I coded (the above is more or less psuedo code and not tested), the above will generate a table variable in SQL and execute an inner join against the desired table (Individuals in this example) and avoid the use of a "IN" statement.
Hope that helps someone out!

Resources