Creating new records in MSACCESS Table - vb.net

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.

Related

Insert text into MS access cells

i am begginer in visual basic and i want to insert text into cells in column in MS access but i doesn't find, how could i do that.
Here is code i tried:
Private Sub UpdateDataBase2()
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
datafile = "F:\Test Database\Database.accdb"
conString = provider & datafile
myConnection.ConnectionString = conString
myConnection.Open()
Dim str As String
str = "Insert into TABLA([LABELS]) Values (?)"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("LABELS", CType(TextBox1.Text, String)))
Select Case panelCount
Case 1
' TextBox1.Text = cmd.Add("LABELS").Rows(0).Item(1).ToString()
Case 2
' str = "Insert into TABLA([LABELS]) Values (?)"
'cmd.Parameters.Add(New OleDbParameter("LABELS", CType(TextBox1.Text, String)))
End Select
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
myConnection.Close()
End Sub
In this application, i made a dynamics panels and labels.(dynamics is for me generated in code)
panelcount is variable which saves to another MS acces database count of dynamics panels. I want to save text from labels to database systematically(it means: text from label 1 insert to cell 1.), but every code i tried was not function for me.
I know i have to use loop, but first i want to try if code works.
Sorry for my english.
Any solution?
Database objects like Connection and Command should be declared in the method where they are used so they can be disposed.
Use Using...End Using blocks to ensure that your database objects are closed and disposed even if there is an error.
Insert creates a new record. If you want to Update an existing record you will need the primary key value for the record you want to update.
Dim Str = Update TABLA Set [LABELS] = ? Where ID = ?
Then you will need a second parameter.
cmd.Parameters.Add("ID", OleDbType.Integer).Value = intID
You will need to declare and provide a value for intID.
Don't show a message box while a connection is open.
Private Sub OPCode()
Try
Dim Str = "Insert into TABLA([LABELS]) Values (?)"
Dim ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Test Database\Database.accdb"
Using myConnection As New OleDbConnection(ConStr),
cmd As OleDbCommand = New OleDbCommand(Str, myConnection)
cmd.Parameters.Add("LABELS", OleDbType.VarChar).Value = TextBox1.Text
myConnection.Open()
cmd.ExecuteNonQuery()
End Using 'Closes and disposes the connection and disposes the command
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

How to restrict user to not update the date and the week textbox

My question is "The user should be able to update (edit) a previously entered log but the date and the week number should be prevented from being edited"
How do I restrict user to not update the date and the week textbox?
Here is my current update code:
Private Sub Btnupdatelog_Click(sender As Object, e As EventArgs) Handles Btnupdatelog.Click
Dim conn As New SqlConnection
Dim cmd As New SqlCommand
cmd = New SqlCommand("update Logbook Objectives='" & Txtobjectives.Text & "',Contents='" & Txtcontent.Text & "',Company_Signature_Stamp='" & Txtsignature.Text & "',Company_Date='" & DateTimePicker2.Text & "' where LogId=" & TxtLogId.Text & "", conn)
conn.ConnectionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Alex\source\repos\CurriculumVitae(CV)\bin\Debug\CurriculumVitae(CV).mdf;Integrated Security=True;Connect Timeout=30"
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
MsgBox("Update Successfully")
End Sub
End Class
To prevent certain fields from being update, simply don't include those fields in the command text. I removed the date field from the text.
Database objects need to be closed and disposed. Using...End Using blocks handle this for you even if there is an error. In this code, both the connection and command are included in the Using block. Note the comma at the end of the first line of the Using.
Never concatenate strings to build sql text. Always use parameters to avoid sql injection. I had to guess at the datatype and size of your fields. Check your database for the correct values.
Private Sub Btnupdatelog_Click(sender As Object, e As EventArgs) Handles Btnupdatelog.Click
Using conn As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Alex\source\repos\CurriculumVitae(CV)\bin\Debug\CurriculumVitae(CV).mdf;Integrated Security=True;Connect Timeout=30"),
cmd As New SqlCommand("update Logbook Set Objectives= #Objectives, Contents= #Contents, Company_Signature_Stamp= #Signature where LogId= #ID;", conn)
With cmd.Parameters
.Add("#Objectives", SqlDbType.VarChar, 300).Value = Txtobjectives.Text
.Add("#Contents", SqlDbType.VarChar, 300).Value = Txtcontent.Text
.Add("#Signature", SqlDbType.VarChar, 100).Value = Txtsignature.Text
.Add("#ID", SqlDbType.Int).Value = CInt(TxtLogId.Text)
End With
conn.Open()
cmd.ExecuteNonQuery()
End Using
MsgBox("Update Successfully")
End Sub

Retrieve data from a specific row entered by inputbox

I have a button and once clicked you are required to enter the customersID and once entered the data from that whole row should then load into the text box's, checkbox etc but when i do it, it prompts me with my own error i created saying Customer not found because it cant locate the ID of some sort? Any help appreciated!
In my opinion - When it loads * (All) from where ID is i am thinking it is only loading in all that data from that specific row at that Customer ID (in which i want) so i could use rows.items etc to load in my required information? Is this correct or? In general i just need help retrieving the data and putting it into my text boxes and such.
Code:
Private Sub Client(ByVal ans As String)
If con.State = ConnectionState.Closed Then con.Open()
cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "Select * FROM tbl WHERE ID = ?"
cmd.Parameters.Add("?", OleDbType.VarChar).Value = ans
If cmd.ExecuteNonQuery() = 0 Then
MsgBox("Does not exist!", MsgBoxStyle.Critical, "Enter new ID!")
Else
MessageBox.Show("Now loaded.", "Search Complete!", MessageBoxButtons.OK, MessageBoxIcon.Information)
If con.State = ConnectionState.Closed Then con.Open()
'create data adapters
sql = "Select * from tbl"
da = New OleDbDataAdapter(sql, con)
da.Fill(ds, "tbl")
RecCnt = ds.Tables("tbl").Rows.Count 'how many records in ds
'assign data to lables
TxtCI.Text = ds.Tables("tbl").Rows(0).Item(0)
con.Close()
End If
cmd.ExecuteNonQuery()
con.Close()
End Sub
Caller (Search button):
Client(custid)
ExecuteNonQuery cannot work correctly with a SELECT statement. The returned value is the number of the rows affected but a SELECT statement doesn't change, insert or delete any row, so it is always zero.
You should use ExecuteReader (and this removes also the need to use an OleDbDataAdapter, a DataTable/Dataset and the long winded statement lines to retrieve values from the DataSet/Tables/Rows/Columns hierarchy
If con.State = ConnectionState.Closed Then con.Open()
cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "Select * FROM tblcustomer WHERE CustomerID = ?"
cmd.Parameters.Add("?", OleDbType.VarChar).Value = ans
Dim reader As OleDbDataReader = cmd.ExecuteReader()
if reader.Read() Then
TxtCI.Text = reader(0).ToString()
TxtName.Text = reader(1).ToString()
... and so on ...
Else
MsgBox("Customer Does not exist!", ....)
Notice that you could substitute the column index (0,1,2 etc...) with the column name ("CI", "Name" etc...). This is somewhat better because it doesn't depend on the order returned by the SELECT * query (Of course, if you change the columns names you have the same problem but, at least, you should know about the change)

No value given for one or more required parameters vb.net oledb

Public Class ViewPhoneRecords
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim da As OleDb.OleDbDataAdapter
Dim ds As New DataSet
Dim sqlquery As New OleDb.OleDbCommand
Dim con1 As New OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Database.accdb")
Private Sub SaveBtn_Click(sender As Object, e As EventArgs) Handles SaveBtn.Click
Dim sqlupdate As String
' Here we use the UPDATE Statement to update the information. To be sure we are
' updating the right record we also use the WHERE clause to be sureno information
' is added or changed in the other records
sqlupdate = "UPDATE PhoneRecords SET Forename=#Forename, Surname=#Surname, Address=#Address, PhoneModel=#PhoneModel, PhoneNumber=#PhoneNumber, Postcode=#Postcode WHERE IDNum='" & IDTextBox.Text & "'"
Dim cmd As New OleDbCommand(sqlupdate, 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("#Forename", ForenameTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#Surname", SurnameTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#Address", AddressTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#PhoneModel", PhoneModelTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#PhoneNumber", PhoneNumberTextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#Postcode", PostcodeTextBox1.Text))
con1.Open()
cmd.ExecuteNonQuery()
MsgBox("Row(s) Inserted !! ") 'Displays message box informing the user that the database has been added to
con1.Close() 'Connection closed
Me.Refresh()
End Sub
This is supposed to update a selected record in a datagrid view. However, when I click the 'Save changes' button, an error is given; "No value given for one or more parameters." Any idea how to solve this?
Use cmd.Parameters.AddWithValue instead of cmd.Parameters.Add

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