Duplicate Random numbers in Visual Studio 2010 - vb.net

I am new to Vb . I am trying to make a project on railway reservation system . I want to generate random ticket number and save it to the ms.access 2007 file . So far , everything is quite working properly but the problem I am having is that when I run the program and book two tickets one after another (without stop debugging ) , it generates two different random ticket numbers and saves them to the ms.access file but when I book one ticket and then stop debugging and after that debug again and book another ticket , it generates the same ticket number as it generated for the first ticket which I booked when I debug for the first time . Could you help me how should I fix this issue ? Thank you !
This is my code
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim value As Integer = CInt(Int((47563 * Rnd()) + 1))
Dim str As String
str = "insert into Table2 ([P_Name], [Age], [Phone], [Train_Name], [Seat_No],[Berth],[Tnumber]) values (?, ?, ?, ?, ?,?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(str, Conn)
cmd.Parameters.Add(New OleDbParameter("P_Name", CType(TextBox1.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Age", CType(TextBox2.Text, Integer)))
cmd.Parameters.Add(New OleDbParameter("Phone", CType(TextBox3.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Train_Name", CType(TextBox4.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Seat_No", CType(TextBox5.Text, Integer)))
cmd.Parameters.Add(New OleDbParameter("Berth", CType(TextBox6.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Tnumber", CType(value, Integer)))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
Conn.Close()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
MsgBox("Ticket Booked Successfully !!! ")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Instead of the Rnd() function, instantiate a Random object and use that.
Dim random As Random = New Random
Dim ticketNumber As Int32 = random.Next(1, 47563)
Note though that this is an absolute TERRIBLE way to generate a ticket number. You will ALWAYS get ticket number collisions if you use random numbers.
Alternative methods would be to use the system date/time (to the millisecond) to generate unique ticket numbers.
Or use a Guid.
Or an AutoNumber (IDENTITY) column in your database.
Or any other method that gives you a non-repeating sequence of numbers / characters.

You can use GUID or Date format for Unuqie Number.
For example:
Now : 2015/03/14 13:10:52 your unique number may be 20150314131052.

Related

Data type mismatch in criteria expression BUT not always, sometimes work, sometimes not vbnet / access

It sometimes work, sometimes doesn't, but it updates the database when it works. I don't really know what's the problem anymore, all I'm inputting are numbers
Dim conn As New OleDbConnection(cs) 'my database path
Dim add As String = "INSERT INTO tblGrades ([Semester], [Subject], [Prelim], [Midterm], [Final], [StudentID]) VALUES (#Semester, #Subject, #Prelim, #Midterm, #Final, #StudentID)"
If cmbSemester.Text = Nothing Or cmbSubject.Text = Nothing Or txtboxPrelim.Text = Nothing Or txtboxMidterm.Text = Nothing Or txtboxFinals.Text = Nothing Then
MsgBox("Fill up the empty box", MsgBoxStyle.Exclamation, "Missing")
Else
conn.Open()
Dim cmd As New OleDbCommand(add, conn)
'Gives a parameter for database column name
cmd.Parameters.Add(New OleDbParameter("Semester", CType(cmbSemester.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Subject", CType(cmbSubject.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Prelim", CType(txtboxPrelim.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Midterm", CType(txtboxMidterm.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Final", CType(txtboxFinals.Text, String)))
cmd.Parameters.Add(New OleDbParameter("StudentID", CType(txtboxStudentID.Text, String)))
cmd.ExecuteNonQuery()
conn.Close()
MessageBox.Show("Add Grades?", "Add Grade Info", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation)
Me.Controls.Clear()
InitializeComponent()
FormModifyGrades_Load(e, e)
Refresh()
End If
End Sub
Data types are string both in codes and in access, since I only need to type the number without any computation, help please, been stuck for hours.
I think you should check a few things.
It seems that you need to find the exact error point by putting a try/catch statement.
You should check the DB Table column type.
ex) input length and attributes
It seems that you should also check the input value in the TextBox. It looks like you need a length check rather than a Notthing check.
TextBox.text = "" (O)
TextBox.Text = Nothing (X) No.

HOW to fix overflow exception while connecting to ms access database from visual basic 2010

I am new to visual basic. I am developing a project in visual basic 2010 for my mini project.I wanted to store my data inserted in visual basic form into the database created in ms access 2007.I have typed the following code but, each time i enter the values into the form and press submit I get the exception as "overflow" in a message box . I couldn't able to find out the reason for this. Please help me out.
THE FOLLOWING IS THE CODE:
Imports System.Data.OleDb
Public Class dn_register
Dim provider As String
Dim dataFile As String
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Private Sub dn_sub_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dn_sub.Click
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
dataFile = "F:\MyDatabase\MyProjectDatabase.accdb"
connString = provider & dataFile
myConnection.Close()
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "Insert into Dnr_tbl([Dname],[Age],[Bloodgroup],[Location],[Contact],[Email]) Values(?,?,?,?,?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("Dname", CType(TextBox1.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Age", CType(TextBox2.Text, Integer)))
cmd.Parameters.Add(New OleDbParameter("Bloodgroup", CType(TextBox3.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Location", CType(TextBox4.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Contact", CType(TextBox5.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Email", CType(TextBox6.Text, String)))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
And here is the snapshot of my error message
My guess is that this line is throwing the exception:
cmd.Parameters.Add(New OleDbParameter("Age", CType(TextBox2.Text, Integer)))
My first suggestion is to use the appropriate control to handle numeric input such as a NumericUpDown control.
My second suggestion (if you continue to use a TextBox) is to explicitly convert the String value to an Integer using Integer.TryParse.
My third suggestion is to stop using CType on String values (textBox[n].Text) to convert them to Strings, it is unnecessary.
My fourth suggestion is to use Parameter.AddWithValue instead since it will use the data type of the value passed.
My fifth and final suggestion is to wrap your objects that implement iDisposable in Using statements or to at least explicitly dispose of them.
Here is an example of implementing suggestions 2-5, if you take my first suggestion, then #2 is unnecessary:
'Declare an age variable that is an Integer
Dim age As Integer
'Convert the String to an Integer
If Integer.TryParse(TextBox2.Text, age) Then
'Declare the connection object
Dim con As OleDbConnection
'Database operations should always be wrapped in Try/Catch
Try
'Set the connection object to a new instance
con = New OleDbConnection(connString)
'Create a new instance of the command object
Using cmd As OleDbCommand = New OleDbCommand("INSERT INTO [Dnr_tbl] ([Dname], [Age], [Bloodgroup], [Location], [Contact], [Email]) VALUES (#name, #age, #bloodgroup, #location, #contact, #email)", con)
'Parameterize the query
With cmd.Parameters
.AddWithValue("#name", TextBox1.Text)
.AddWithValue("#age", age)
.AddWithValue("#bloodgroup", TextBox3.Text)
.AddWithValue("#location", TextBox4.Text)
.AddWithValue("#contact", TextBox5.Text)
.AddWithValue("#email", TextBox6.Text)
End With
'Open the connection
con.Open()
'Execute the query
cmd.ExecuteNonQuery()
'Close the connection
con.Close()
'Clear the controls
TextBox1.Clear() : TextBox2.Clear() : TextBox3.Clear() : TextBox4.Clear() : TextBox5.Clear() : TextBox6.Clear()
End Using
Catch ex As Exception
MessageBox.Show(ex.ToString())
Finally
'Check if the connection object was initialized
If con IsNot Nothing Then
If con.State = ConnectionState.Open Then
'Close the connection if it was left open(exception thrown)
con.Close()
End If
'Dispose of the connection object
con.Dispose()
End If
End Try
Else
MessageBox.Show("Invalid age input.")
End If
First try to narrow down which parameter is causing the problem. You can either comment out all of the parameters and add them back until you find the problem (adjusting the SQL statement as needed to match the parameter count) or pick a likely suspect and comment it out and continue commenting out parameters and adjusting the SQL statement until it works. You may need to temporarily tweak the table in Access to allow nulls in the tested columns. The integer value does seem a likely candidate and I would start from there.
Once you find the problem parameter, it may be obvious that there's a datatype conflict or mismatch between VB.NET and Access or you may have to experiment a little to find which VB cast will work. The next most likely candidate in your example would be a string length problem and that would be pretty obvious from looking at the table definition and your text box input length limits.

give me a same code for deleting purposes..vb.net 2010 - closed

The code below is my code for saving records
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
'Change the following to your access database location
dataFile = "C:\Users\DELL\Downloads\WindowsApplication1\WindowsApplication1\Database1.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "insert into tblODR ([ID], [Office], [Elements], [Objectives], [Initiatves]) values (?, ?, ?, ?, ?)"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("ID", CType(IDTextBox.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Office", CType(OfficeTextBox.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Elements", CType(ElementsTextBox.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Objectives", CType(ObjectivesTextBox.Text, String)))
cmd.Parameters.Add(New OleDbParameter("Initiatves", CType(InitiatvesTextBox.Text, String)))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
Me.Validate()
Me.TblODRBindingSource.EndEdit()
Me.TblODRTableAdapter.Update(Me.Database1DataSet.tblODR)
Catch ex As Exception
MsgBox(ex.Message)
End Try
can anyone give me a same code BUT, for deleting purposes.. the code above adds a new record and shows instantly in the datagridview after adding it..(before i have code for adding purposes but it wont add instantly in the datagridview)..
What i want is, a code that when i delete a record using a textbox (i'm deleting records by inputting the ID Number of a record in a textbox)..the deleted record will show instantly after deleting it.. (my code as of now, when i delete a record, it would delete the record BUT i have to close the form and run the program again to show if the deleted record have been deleted)
You can use gridview1.refresh() method to refresh your grid on the delete button , so when delete common executes, it will refresh your gridview to update the new record use gridview1.update() to update the changes that you have made. Or you can also make your own method to refresh your gridview,here is the sample method to refresh the grid like this
Public Sub Gridrefresh(ByVal s As String, ByVal dgv As DataGridView)
Dim dt As New DataTable()
Dim cmd As New SqlCommand("select * from " + s + "", con.dbconnection())
cmd.CommandType = CommandType.Text
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
dgv.DataSource = dt
End Sub
here s represent name of your table , when you call this method u can use like this Gridrefresh("name of table ",datagridView1 name ), Hope this will help you

Creating new records in MSACCESS Table

I am attempting to create a new record from vb.net to an msaccess table, which i am able to do, but i have to add in the next consecutive ID number for it to actually save. For instance, if the next ID in the Access DB is 4, i have to type in 4 in the id textfield on my form. Code below:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim sqlinsert As String
' We use the INSERT statement which tells our program to add the information
' from the Forms Text fields into the Databases columns.
sqlinsert = "INSERT INTO Table1(Title, YearofFilm, Description, Field1, ID)" & _
"VALUES(#Title, #YearofFilm, #Description, #Field1, #ID)"
Dim cmd As New OleDbCommand(sqlinsert, con1)
' This assigns the values for our columns in the DataBase.
' To ensure the correct values are written to the correct column
cmd.Parameters.Add(New OleDbParameter("#Title", TextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#YearofFilm", Convert.ToInt32(TextBox2.Text)))
cmd.Parameters.Add(New OleDbParameter("#Description", TextBox3.Text))
cmd.Parameters.Add(New OleDbParameter("#Field1", TextBox4.Text))
cmd.Parameters.Add(New OleDbParameter("#ID", Convert.ToInt32(TextBox5.Text)))
' This is what actually writes our changes to the DataBase.
' You have to open the connection, execute the commands and
' then close connection.
con1.Open()
cmd.ExecuteNonQuery()
con1.Close()
' This are subs in Module1, to clear all the TextBoxes on the form
' and refresh the DataGridView on the MainForm to show our new records.
ClearTextBox(Me)
RefreshDGV()
Me.Close()
End Sub
How can i tell textbox5 which is the ID field, to be the next number in the access db?
Open your Access database, show the structure of your table and change the ID field type from numeric to AutoNumber.
Now your code don't need to pass anything to Access because the number will be handled automatically from Access.
You could just add these lines to your code to get back the number assigned by Access to your field
Dim sqlinsert As String
sqlinsert = "INSERT INTO Table1(Title, YearofFilm, Description, Field1)" & _
"VALUES(#Title, #YearofFilm, #Description, #Field1)"
Dim cmd As New OleDbCommand(sqlinsert, con1)
cmd.Parameters.Add(New OleDbParameter("#Title", TextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#YearofFilm", Convert.ToInt32(TextBox2.Text)))
cmd.Parameters.Add(New OleDbParameter("#Description", TextBox3.Text))
cmd.Parameters.Add(New OleDbParameter("#Field1", TextBox4.Text))
con1.Open()
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
cmd.CommandText = "SELECT ##IDENTITY"
Dim assignedID = Convert.ToInt32(cmd.ExecuteScalar())
' Eventually
TextBox5.Text = assignedID.ToString
con1.Close()
......
See also
How to retrieve last autoincremented value in MS-Access like ##Identity in Sql Server
Create a SELECT statement to retrieve the Max number form the table and add one to it. I do not know VB.Net, so it should be something like.
maxQry = "SELECT Max(IDColumnName) As MaxID FROM theTableName;"
Dim cmd As New OleDbCommand(maxQry, con1)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read()
TextBox5.Text = dr("MaxID").ToString
End While
End If
Unless the field is an AutoNumber type you do not have to worry about it at all.

OleDB INSERT STATEMENT Error

I'm working on a project where I'm going to add records in database. My big problem is the "INSERT INTO" statement, after searching and debugging still no success. This is a part of the code:
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim sqlinsert As String = "INSERT INTO tblList([Access Number],[Book Title],Subject,Author,Edition,Page,Publisher,Years,Copy)" & "VALUES(#Access Number,#Book Title,#Subject,#Author,#Edition,#Page,#Publisher,#Years,#Copy)"
Dim cmd As New OleDbCommand(sqlinsert, con)
cmd.Parameters.Add(New OleDbParameter("#Access Number", txtan.Text))
cmd.Parameters.Add(New OleDbParameter("#Book Title", txtbt.Text))
cmd.Parameters.Add(New OleDbParameter("#Subject", txtsub.Text))
cmd.Parameters.Add(New OleDbParameter("#Author", txtau.Text))
cmd.Parameters.Add(New OleDbParameter("#Edition", txted.Text))
cmd.Parameters.Add(New OleDbParameter("#Page", txtpg.Text))
cmd.Parameters.Add(New OleDbParameter("#Publisher", txtpub.Text))
cmd.Parameters.Add(New OleDbParameter("#Years", txtyr.Text))
cmd.Parameters.Add(New OleDbParameter("#Copy", txtco.Text))
cmd.ExecuteNonQuery()
MsgBox("One Record Added")
Refreshlist()
clear()
End Sub
Help me please? I am so confused.
Thanks a lot.
(A am using ms access and vb.net in visual studio 2008)
Upon digging on some of my old programs, this is how I pass parameters to ms access:
Dim sqlinsert As String= "INSERT INTO tblList([Access Number],[Book Title],Subject,Author,Edition,Page,Publisher,Years,Copy)" & _
"VALUES(?,?,?,?,?,?,?,?,?)"
Dim cmd as new OleDbCommand(sqlinsert, con)
cmd.Connection.Open
With cmd.Parameters
.AddWithValue("access_number", txtan.text)
.AddWithValue("book_title", txtbt.text)
.AddWithValue("subject", txtsub.text)
.AddWithValue("author", txtau.text)
.AddWithValue("edition", txted.text)
.AddWithValue("page", txtpg.text)
.AddWithValue("publisher", txtpub.text)
.AddWithValue("years", txtyr.text)
.AddWithValue("copy", txtco.text)
End With
cmd.ExecuteNonQuery()
Also, I'd be wary of using spaces on your column names,
specifically on Access Number and Book Title
P.S.
.AddWithValue("a", b)
a = this can be anything but as a personal rule of mine, i tend to name it based on the column name
b = the value you want to pass
Try change the name of these parameters from
"#Access Number" to: "#Access_Number"
"#Book Title" to: "#Book_Title"