Print in VB.NET 2010 - vb.net

I want to print on a Passbook (paper book used to record bank transactions) using a passbook printer (Epson PLQ 20) Using VB.NET 2010.
My current mysql table structure is,
1. tblLoanRegistry(LoanID pk, EMPNumber, Date, Amount, NoOfInstallments, Teller)
2. tblLoanAccount(ID pk, LoanID fk, Date, Payment, Interest, Total, Auto bool, Installment int, teller)
My problems are:
How to detect the last row printed?
How to print the first row that not printed, on the correct position of the book (Correct line).
I have decided to add a field "Printed" (Boolean) in each table above mentioned. To get the printed or not. I can print text, numbers etc using the same printer in vb.net (Eg: Account holders details on the front page). But I'm facing above mentioned problems when printing transactions. Your help/ opinions highly appreciated.
More Information:
Actually I developed a web based account handling system using php and mysql for a non profit organisation as the my project of the degree. Now they want to print transactions on a passbook as I described before.
Therefore I am creating an application using VB.NET (I am totally new to VB.NET. But have experience in vb6) while I am learning it. I have managed to simple printing but this is something different.
I have no good idea to solve above mentioned two problems.
Update:
I did it in different (may be a bad) way.
On click event of the print button.
Dim sqlLoan As String
conn = New MySqlConnection(cnString)
sqlLoan = "SELECT tblLoanAccount.Date,if(Installment = 0, 'Interest', concat('Installment : ', Installment)) as Description, tblLoanAccount.Payment, tblLoanAccount.Interest, " &
" tblLoanAccount.Total, tblLoanAccount.Auto, tblLoanAccount.Installment FROM tblLoanAccount join tblloanRegistry on tblloanRegistry.LoanID = tblLoanAccount.LoanID " &
" where(tblloanRegistry.EMPNumber = " & cmbEMPN.Text & " And tblLoanAccount.LoanID = tblLoanRegistry.LoanID) AND tblLoanAccount.Total <> 0 ORDER BY tblLoanAccount.ID"
Using conn As New MySqlConnection(cnString)
Using cmd As New MySqlCommand(sqlLoan, conn)
conn.Open()
Using myReader As MySqlDataReader = cmd.ExecuteReader()
Using writer As StreamWriter = New StreamWriter("c:\file.txt")
While myReader.Read()
writer.WriteLine("{0}, {1}, {2}, {3}, {4}", myReader.Item(0), myReader.Item(1), myReader.Item(2), myReader.Item(3), myReader.Item(4))
End While
End Using
Call Printing()
End Using
End Using
End Using
' Print the file.
Public Sub Printing()
Try
streamToPrint = New StreamReader(("c:\file.txt"))
Try
printFont = New Font("Arial", 10)
Dim pd As New PrintDocument()
AddHandler pd.PrintPage, AddressOf pd_PrintPage
' Print the document.
pd.Print()
Finally
streamToPrint.Close()
End Try
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub 'Printing
And other codes are as msdn PrintDocument Class.

There are a lot of unknowns in this question. For example, when you mark an item as printed, do you want to mark it universally (for all applications, all transactions and all time) or only within a limited context (a particular application, transaction or time frame)?
Is a transaction started and completed within a single .NET thread, or is this application multi-threaded, or does the transaction span across multiple independent executions? Do you need some record of an item having been printed beyond the physical piece of paper?
Assuming you want a record of an item having been printed only within a particular transaction, you may want to create a third table, called something like tblPrintTransaction, with a Primary Key or other identifier column and any additional columns you desire (transaction start date, end date, user ID, contextual information, etc.). When you start your application, create a new row in this table and get the row ID.
Now, create a fourth table, called something like tblPrintTransactionArtifact, with at least two columns. One column will be a foreign key identifying the transaction (from the tblPrintTransaction table) and one or more columns will be used to identify the item that has been printed. For example, your table could contain two columns to identify the printed item: one column specifying either "Registry" or "Account" and another specifying the item's ID.
Of course, all of this information could be created and maintained within the application itself (using variables, etc), but storing them in a table means they will persist beyond the execution of the application, giving you a permanent record. I would recommend that you keep track of the current "line" on the printed page within the application as I see little use for this within your database.

Dim sqlLoan As String
conn = New MySqlConnection(cnString)
sqlLoan = "SELECT tblLoanAccount.Date,if(Installment = 0, 'Interest', concat('Installment : ', Installment)) as Description, tblLoanAccount.Payment, tblLoanAccount.Interest, " &
" tblLoanAccount.Total, tblLoanAccount.Auto, tblLoanAccount.Installment FROM tblLoanAccount join tblloanRegistry on tblloanRegistry.LoanID = tblLoanAccount.LoanID " &
" where(tblloanRegistry.EMPNumber = " & cmbEMPN.Text & " And tblLoanAccount.LoanID = tblLoanRegistry.LoanID) AND tblLoanAccount.Total <> 0 ORDER BY tblLoanAccount.ID"
Using conn As New MySqlConnection(cnString)
Using cmd As New MySqlCommand(sqlLoan, conn)
conn.Open()
Using myReader As MySqlDataReader = cmd.ExecuteReader()
Using writer As StreamWriter = New StreamWriter("c:\file.txt")
While myReader.Read()
writer.WriteLine("{0}, {1}, {2}, {3}, {4}", myReader.Item(0), myReader.Item(1), myReader.Item(2), myReader.Item(3), myReader.Item(4))
End While
End Using
Call Printing()
End Using
End Using
End Using
' Print the file.
Public Sub Printing()
Try
streamToPrint = New StreamReader("c:\file.txt")
Try
printFont = New Font("Arial", 10)
Dim pd As New PrintDocument()
AddHandler pd.PrintPage, AddressOf pd_PrintPage
' Print the document.
pd.Print()
Finally
streamToPrint.Close()
End Try
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub 'Printing
And other codes are as msdn PrintDocument Class.

You can try to use the easy to use, lightweight report writer I use with MySql & VB.Net at http://www.jcl.vdtec.net

Related

Read CSV to series of existing textbox in Vb.net

I have a code to import csv to auto generated text box which was a part of my previous app. However I had to re do the whole script which involves importing csv to multiple existing textbox.
Below is my old code which worked like a charm but in this code my textbox were getting auto generated based on the numbers of value present in my csv.
Dim T(100) As TextBox
Using ofd As New OpenFileDialog()
If ofd.ShowDialog() = DialogResult.OK Then
TextBox1.Text = (ofd.FileName)
End If
Using MyReader As New Microsoft.VisualBasic.
FileIO.TextFieldParser(TextBox1.Text)
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim numer As Integer
Dim currentRow As String()
numer = 1
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
If (currentField IsNot "") Then
Dim myTB As New TextBox
T(numer) = myTB
myTB.Text = currentField
myTB.Visible = True
myTB.Location = New Point(550, 92 + (numer * 28))
myTB.Name = "ADBox" + numer.ToString
myTB.ReadOnly = True
Me.Controls.Add(myTB)
numer += 1
End If
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try
End While
End Using
End Using
But that created a lot of issue in my app hence I had to load the values on an existing textboxes(Multiple) but I am somehow not able to.
Edit1:
*** The code above creates a textbox and adds my csv values to it and what I am looking for is inject csv to existing textbox which I have created and not automatically generated text box.
For Example my code creates text box called ADUser1,2,3,4 and enters all the value but my following code which will create a textfile by fetching the values from the text box is not working because when I declare
My.Computer.FileSystem.WriteAllText(aduser1, ADBox1.Text, True)
it says it doesn't exists because when a form loads it never created such textboxes. This is the challenge I am facing
Any help will be a great value
Thanks
I agree that this is a very awkward design and should be redone, but for the purpose of answering your question...
The reason your code here: My.Computer.FileSystem.WriteAllText(aduser1, ADBox1.Text, True) doesn't find ADBox1 is that it is not created and referenced like an object you drag on to the form. It could be, by the way, but that is more work than dragging and naming 100+ text boxes on your form. Nuts. Creating the textboxes in code is better.
If you "manually" add one textbox to a form, then examine the designer-generated code for the form you will see that it created a textbox for you. You would find something similar to Friend WithEvents ADBox1 As System.Windows.Forms.TextBox. This is the reason you can reference the textbox in your form code. There is no magic here and you are technically doing the same thing in your code, here:
Dim T(100) As TextBox
...
Dim myTB As New TextBox
T(numer) = myTB
You can use the reference T(n) to refer to any of your textboxes. It is not clear where the WriteAllText function is but you may need to be sure Dim T(100) As TextBox is a form global, then change the WriteAllText line like this to get at ADBox1:
My.Computer.FileSystem.WriteAllText(aduser1, T(1).Text, True)

Get First & Last Name of All AD Accounts

I'm looking for the quickest and easiest way to retrieve all Active Directory account's first & last names. The intention is to have a string list which contains all names from the Active Directory, for the purpose of auto-completion in a textbox in a small Visual Basic application used for unlocking accounts.
Usage Scenario:
On form load the application generates the list of names from the AD. I'm expecting this to take around 10-15 seconds as there's 4,500 accounts on the AD. Each name is added to a string list for use with the auto completion.
The user types the name Garry into textbox1 and the auto complete suggests all Garry's in the AD, by using a string list. I know how to do this easily, I just dont know how to populate the list with user's names efficiently.
There's a lot of samples on accessing the AD, but none which show how to loop through it. I thought asking on here would help both myself and other users in a similar usage case.
The code I have so far for accessing a single account is shown below, however I need to loop through all AD accounts and retrieve their First & Last names.
Current Code to access single account:
'Domain is declared with the LDAP path
'UserName is declared with textbox1.text value
Dim ADEntry As New DirectoryServices.DirectoryEntry("LDAP://" & Domain)
Dim ADSearch As New System.DirectoryServices.DirectorySearcher(ADEntry)
ADSearch.Filter = ("(samAccountName=" & UserName & ")")
ADSearch.SearchScope = System.DirectoryServices.SearchScope.Subtree
Dim UserFound As System.DirectoryServices.SearchResult = ADSearch.FindOne()
If Not IsNothing(UserFound) Then
Log.AppendLine("Account found, loading checks...")
Dim Attrib As String = "msDS-User-Account-Control-Computed"
Dim User As System.DirectoryServices.DirectoryEntry
User = UserFound.GetDirectoryEntry()
User.RefreshCache(New String() {Attrib})
'Display user account details
txtLogin.Text = User.Properties("userPrincipalName").ToString
txtName.Text = User.Properties("givenName").ToString & " " & User.Properties("sn").ToString
else
'User not found
end if
Any help would be much appreciated, even in C#.
You can use the same ADEntry variable as above and do something like this. This only adds a user to the list if they have both a first and last name.
Dim listNames As New AutoCompleteStringCollection
Using ADSearch As New DirectoryServices.DirectorySearcher(ADEntry, "(&(objectCategory=person)(objectClass=user))", {"givenName", "sn"}, DirectoryServices.SearchScope.Subtree)
For Each user As DirectoryServices.SearchResult In ADSearch.FindAll
Try
listNames.Add(user.GetDirectoryEntry.Properties("givenName").Value.ToString + " " + user.GetDirectoryEntry.Properties("sn").Value.ToString)
Catch ex As Exception
End Try
Next
End Using
With TextBox1
.AutoCompleteCustomSource = listNames
.AutoCompleteMode = AutoCompleteMode.SuggestAppend
.AutoCompleteSource = AutoCompleteSource.CustomSource
End With

Updating row in database using vb.net

I am trying to update and save a row of a database table. I have used a version of this code to just populate a GridView and it works, so I am assuming it has something to do with my SQL statment; I do not get an error, the table just does not update. On the page load event I have the textboxes being populated by the information of the row, and I have a global variable, named 'temp', that will save the title of the row so I can use it in the button's click event. The error I am getting states that I have not given a value for one of my required parameters. My Locals tab on the debugger shows that every variable has a value, though the one I try to update is not the new data but still the old data.
I have looked at several examples and I cannot find the problem though. Thank you for any assistance.
Protected Sub btnSave_Click(sender As Object, e As EventArgs)
Dim strTitle As String = txtTitle.Text
Dim strConsole As String = txtConsole.Text
Dim strYear As String= txtYear.Text
Dim strPurchase As String = calDate.SelectedDate.ToString
Using con As OleDbConnection = New OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;" + "DATA SOURCE=" + Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "App_Data", "db1.accdb"))
Dim cmd As OleDbCommand = New OleDbCommand()
cmd.CommandText = Convert.ToString("UPDATE Video_Games SET Title = #title, Console = #Console, Year_Released = #Year_Released, Purchase = #Purchase WHERE Title=" & temp)
cmd.Connection = con
cmd.Parameters.AddWithValue("#Title", strTitle)
cmd.Parameters.AddWithValue("#Console", strConsole)
cmd.Parameters.AddWithValue("#Year_Released", strYear)
cmd.Parameters.AddWithValue("#Purchase", strPurchase)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
Server.Transfer("Form.aspx", True)
End Sub
I have also tried the have my where statement as: WHERE Title='" & temp & "'") Though this does not work either.
This is the details of the Error message
I changed you commandText as seen below and created a blank database with a table named just like yours and the update worked
cmd.CommandText = "UPDATE Video_Games SET Title = #title, Console = #Console, Year_Released = #Year_Released, Purchase = #Purchase WHERE Title='" & temp & "'"
I set my variable for Title = Super Mario Bros and then the temp variable to Wario World. I had a record in my database with the title of Wario World, and running the update changed the title to Super Mario Bros.
Check if you temp variable is different from your #title variable. Also check that you have the record int the table for your temp variable title
Thank you all for your assistance, This is such a wonderful community.
The problem, I found out, does not even have to do with the button's click event, it had to do with the page load event. Since on page load the row's information is loaded and populated into the textboxes, when the button is clicked to update the fields, the page load event triggers again and reloads the old information into fields, essentially saving the old information instead of the new. My fix was to create an If Not IsPostBack Then statement that encapsulates my on page load code. Therefore the code does not get saved when the button is pressed. Another this, I did not need the temp variable, using WHERE Title='" + strTitle + "'" worked. Hopefully this helps other people stuck on a similar problem!
Using dates in a where clause is always ify as they are floating point numbers and may not match equally. I'd try and round them or convert them to strings before comparison, e.g. something along these lines:
UPDATE Video_Games SET Title = #title, Console = #Console, Year_Released = #Year_Released, Format(Purchase, ""m/d/yyyy"") = Format(#Purchase, ""m/d/yyyy"") WHERE Title = #Title

Syntax Error in INSERT INTO statement vb.net and an access database

The program I'm writing (in vb.net) is supposed to be loading values from text boxes into a database.
However, when I click "Save", at first nothing at all happened. No error, no notification, nothing. So I traced it using breakpoints, and it got to:
daTraining.Update(dsTraining, "Training")
and just stopped.
So I put in a try/catch, and now when I hit save I get
System.Data.OleDB.OledgException (0x80040E14): Syntax error in INSERT INTO statement.
I'm confused on how to troubleshoot this or what the issue might be.
The Code
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Try
Dim cb As New OleDb.OleDbCommandBuilder(daTraining)
Dim dsNewRow As DataRow
dsNewRow = dsTraining.Tables("Training").NewRow
dsNewRow.Item("ID") = txtTrainingID.Text
dsNewRow.Item("Ranch") = cbRanches.Text
dsNewRow.Item("Location") = txtLocation.Text
dsNewRow.Item("Date") = mtbDate.Text
dsNewRow.Item("StartTime") = mtbStartTime.Text
dsNewRow.Item("FinishTime") = mtbFinishTime.Text
dsNewRow.Item("Crew") = txtCrews.Text
dsNewRow.Item("Supervisor") = txtSupervisor.Text
dsNewRow.Item("Foreperson") = txtForeperson.Text
dsNewRow.Item("Activity") = txtActivity.Text
dsNewRow.Item("Trainer") = txtTrainer.Text
dsNewRow.Item("Topics") = txtTopics.Text
dsTraining.Tables("Training").Rows.Add(dsNewRow)
daTraining.Update(dsTraining, "Training")
MsgBox("Training Recorded")
cb.Dispose()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
This is a common issue when using a data adapter with a wildcard in the query and a command builder. If one or more of your columns names is a reserved word or contains spaces or other special characters then the auto-generated INSERT and UPDATE statements will generate syntax errors.
The preferred solution is to change the offending column name(s) but, if that's not an option, you can set the QuotePrefix and QuoteSuffix properties of your command builder so that it escapes all column names in the generated action commands. The appropriate values will vary depending on your database but for Microsoft databases, use "[" and "]" respectively.
As indicated in comments, the issue was in
dsNewRow.Item("Date") = mtbDate.Text
with Date being a reserved word.

Refresh combo box in Windows Form

HI,
This question has been asked a lot on the web but all of them seems to be confused with windows forms and asp.net forms so I had to finally come here for answer.
I have a Main form (a window form) in VB.NET which has a Combo Box to display a list of countries. A sub form activated from a "Button" on the Main form allows users to add Countries to their list. But After Adding a new entry the Combo Box on the Main form does not show the update (while it is still open). I have to exit the main form and relaunch it to see the update.
The populate function in shown below. I call this method after adding new countries but still; not good. I have used Invalidate function of combo box but of no use as well.
Any Help is appreciated. Thanks
Public Sub PopulateCountry()
Dim rsLocal As New ADODB.Recordset
Try
Dim sSQLCommand As String
Me.CountryList.Items.Clear()
'get the list of countries from the local database
sSQLCommand = " SELECT * FROM CountryList order by CountryDesc"
rsLocal.Open(sSQLCommand, cnn, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic)
'Display All the countries
While rsLocal.EOF = False
Dim Country As New modGV.cbItem
Country .ID = rsLocal.Fields("CountryID").Value
Country.name = rsLocal.Fields("Country Desc").Value.ToString.Trim
Me.CountryList.Items.Add(Country)
rsLocal.MoveNext()
End While
rsLocal.Close()
Catch ex As Exception
Debug.WriteLine("PopulateCountry: exception occurred " & ex.Description)
Finally
If rsLocal.State = ConnectionState.Open Then
rsLocal.Close()
End If
End Try
End Sub
Use object.refresh
http://www.devx.com/vb2themax/Tip/18646