I am trying to add a new order into my database using this code. I have used the same code before however its not working now. Can you please help?
I am using Microsoft Visual Basic 2008 express edition and Microsoft Access.
I have four tables.
CurrentRowNo = 0
' Purpose: Add new Account record and assign its default values
' Clear the Account table in the DataSet ready for a new record to be added
SandRDataSet.Tables("Stock").Clear()
'Add a new record to the studnet table
Dim driveletter As String = Application.StartupPath.Substring(0, 1)
Dim cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & driveletter & ":\raheem\Computing\Database\SandR.accdb")
cn.Open()
Dim daStock As New OleDbDataAdapter("SELECT * FROM Stock;", cn)
Dim sqlcmdbldStudent As New OleDb.OleDbCommandBuilder(daStock)
'Fill the database
daStock.Fill(SandRDataSet, "Stock")
Dim test As DataRow = SandRDataSet.Tables("Stock").NewRow
test("Product/Service number") = txtProductNo.Text
test("Product/ Service name") = txtProductName.Text
test("minimum level") = txtMin.Text
test("maximum level") = txtMax.Text
test("Quantity") = txtQuantity.Text
test("Price") = txtPrice.Text
SandRDataSet.Tables("Stock").Rows.Add(test)
sqlcmdbldStudent.GetInsertCommand()
daStock.InsertCommand = sqlcmdbldStudent.GetInsertCommand
daStock.Update(SandRDataSet.Stock)
DisplayAccount()
cn.Dispose()
cn.Close()
If you really have that column names in your table (Space and forward slashes) then I suggest you to set the QuotePrefix and QuoteSuffix to your OleDbCommandBuilder
Dim sqlcmdbldStudent As New OleDb.OleDbCommandBuilder(daStock)
sqlcmdbldStudent.QuotePrefix = "["
sqlcmdbldStudent.QuoteSuffix = "]"
This will force the fields names created by the command builder to be enclosed in square brackets and correctly interpreted by the database engine
Related
I am using below code to query Active Directory and get list of users. The code is working in VB Macro. I modified a bit syntactically to make it work on VB.NET (VS 2022).
The RecordCount is appearing as 900 but I am not able to bind it to DataGridView. Not enough knowledge of VB. I referred to samples which use OleDB DataAdapter but in the code below the command object is different so it throws error.
Also, this line throws error. It is working in Excel Macro.
oCommand1.Properties("SearchScope") = 2
Please advise how to display records in Grid:
'Open the connection.
'This is the ADSI OLE-DB provider name
oConnection1.Provider = "ADsDSOObject"
oConnection1.Open("Active Directory Provider")
oCommand1.ActiveConnection = oConnection1
strQuery = "select c, l, SAMAccountName,displayName, distinguishedName, cn, sn,givenName,title,mail, department, manager, userAccountControl " &
" from 'GC://dc=TestAD,dc=net'" &
"WHERE objectCategory='Person'" &
"AND objectClass='user'"
oCommand1.CommandText = strQuery
oCommand1.Properties("SearchScope") = 2
rs = oCommand1.Execute()
lblRecords.Text = rs.RecordCount
DataGridView1.DataSource = rs
oConnection1.Close()
Use Directory services and LDAP query :
Imports System.DirectoryServices
{......}
Dim oD As DirectoryEntry
Dim oS As DirectorySearcher
oD = New DirectoryEntry("LDAP://RootDSE")
oS = New DirectorySearcher(oD)
oS.Filter = "(&(objectClass=user))"
oS.SearchScope = SearchScope.Subtree
''''''''''''''''''''''
'by default all objects property will be retrieve
'if you just need somme of them use
'oS.PropertiesToLoad.Add("SAMAccountName")
'oS.PropertiesToLoad.Add("displayName")
'oS.PropertiesToLoad.Add("CN")
'etc...
'that will speed up search
''''''''''''''''''''''
Dim src As SearchResultCollection = oS.FindAll()
oD.Close()
oS.Dispose()
Dim dt As New DataTable()
dt.Columns.Add("samaccountname")
dt.Columns.Add("givenName")
dt.Columns.Add("sn")
dt.Columns.Add("mail")
' add here others columns needed in dt
For Each sr As SearchResult In src
Dim dr As DataRow = dt.NewRow()
Dim de As DirectoryEntry = sr.GetDirectoryEntry()
dr("samaccountname") = de.Properties("samaccountname").Value.ToString()
dr("givenName") = de.Properties("givenName").Value.ToString()
dr("sn") = de.Properties("sn").Value.ToString()
dr("mail") = de.Properties("mail").Value.ToString()
'etc... fill others dt columns based on propertys needed
dt.Rows.Add(dr)
de.Close()
Next sr
lblRecords.Text = dt.rows.count-1
DataGridView1.DataSource = dt
I am trying to add a new record to an Access database. I am new to Visual Basic but have been searching for an answer to this. Here is my code so far:
Dim ID As Integer = CInt(IDBox.Text)
Dim password As Integer = CInt(PasswordBox.Text)
Dim first As String = FirstName.Text
Dim last As String = LastName.Text
Dim access As Integer = CInt(AccessLevel.Text)
Dim conn As New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Tristan\Documents\Visual Studio 2015\Projects\Keno\Keno\Users.accdb")
conn.Open()
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
da = New OleDb.OleDbDataAdapter("SELECT * FROM Users", conn)
da.Fill(ds, "Users")
Dim cb As New OleDbCommandBuilder(da)
Dim dsNewRow As DataRow
dsNewRow = ds.Tables("Users").NewRow()
dsNewRow.Item("ID") = ID
dsNewRow.Item("First_Name") = first
dsNewRow.Item("Last_Name") = last
dsNewRow.Item("Password") = password
dsNewRow.Item("Access_Level") = access
ds.Tables("Users").Rows.Add(dsNewRow)
cb.GetInsertCommand()
da.Update(ds, "Users")
conn.Close()
MsgBox("User added successfully!")
Running this gets an error:
An unhandled exception of type System.Data.OleDb.OleDbException
occurred in System.Data.dll
Additional information: Syntax error in INSERT INTO statement.
Any help is appreciated!
The issue is almost certainly the fact that "Password", which you have used as a column name, is a reserved word. Any identifiers used in SQL code that are reserved words or contain special characters, e.g. spaces, must be escaped. A command builder doesn't do that by default. You have to set the QuotePrefix and QuoteSuffix properties yourself to make it do so. For an Access database, you would use "[" and "]" as the property values respectively.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I am trying to create a ticket system, this part of the system will display all of the acts performing on each specific day. I am also trying to show how many tickets/seats are available. I have a database with all seat locations and a boolean value to show if they are taken or not.
Public ds As New DataSet 'used to store the basic elements of the database
Public con As New OleDb.OleDbConnection 'used to connect to the database
Public provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Public datafile As String = "Resources/database.accdb" 'database location and version
Public da As OleDb.OleDbDataAdapter
Public sqlstatement As String
Public connString As String = provider & datafile
lbxActs.Items.Clear()
Dim oDataRowView As DataRowView
Dim sSelectedAssetType As String
ds.Clear()
con.ConnectionString = connString
con.Open()
sqlstatement = "SELECT ShowDate FROM AvailableDates"
da = New OleDb.OleDbDataAdapter(sqlstatement, con)
da.Fill(ds, "Dates")
lbxDates.DataSource = ds.Tables("Dates")
lbxDates.DisplayMember = "ShowDate"
lbxDates.ValueMember = "ShowDate"
con.Close()
oDataRowView = CType(Me.lbxDates.SelectedItem, DataRowView)
sSelectedAssetType = oDataRowView("ShowDate").ToString
lbxActs.Items.AddRange(IO.File.ReadAllLines("Resources/" & sSelectedAssetType & ".txt"))
con.Close()
ds.Clear()
con.ConnectionString = connString
con.Open() 'Open connection to the database
sqlstatement = "SELECT * FROM [Seats" & sSelectedAssetType & "] WHERE [Available] = True "
da = New OleDb.OleDbDataAdapter(sqlstatement, con)
da.Fill(ds, "seats") 'Fill the data adapter
con.Close()
Dim recordCount, x As Short
recordCount = 0
x = 0
recordCount = ds.Tables("seats").Rows.Count
tbxLeftS.Text = recordCount
the first part of the program puts all the show dates into a list box, then depending on which one is clicked it shows a different list of acts from my text files. The second part of the program is supposed to use an SQL statement to find all the seat locations which are available. Then it counts the records and then displays the number in a text box.
Object reference not set to an instance of an object
This error appears 4 times and it highlights this line:
sSelectedAssetType = oDataRowView("ShowDate").ToString
To get rid of the error, its very likely that somehow oDataRowView is null. You need to check to make sure its not null before you try to convert it to a string. Do something like this:
IF Not isdbnull(oDataRowView)
oDataRowView = CType(Me.lbxDates.SelectedItem, DataRowView)
End if
As to why you are getting a null value for oDataRowView, that will require you to debug further. Perhaps it could be an issue with PostBack (assuming this is a web page and not winforms.
This is a new concept for me and I can't quite see what's causing the error
I'm attempting to populate a datagridview control from a single field in an Access database (from a combo and Text box source).
Using literals works, but not with the parameter.
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Backend & ";Persist Security Info=False;")
Dim command As New OleDbCommand("Select Year from tblTest ", conn)
Dim criteria As New List(Of String)
If Not cboYear.Text = String.Empty Then
criteria.Add("Year = #Year")
command.Parameters.AddWithValue("#Year", cboYear.Text)
End If
If criteria.Count > 0 Then
command.CommandText &= " WHERE " & String.Join(" AND ", criteria)
End If
Dim UserQuery As New OleDbDataAdapter(command.CommandText, conn)
Dim UserRet As New DataTable
UserQuery.Fill(UserRet)
With frmDGV.DataGridView2
.DataSource = UserRet
End With
frmDGV.DataGridView2.Visible = True
frmDGV.Show()
Trying to Fill the datatable shows exception 'No value given for one or more required parameters.'
The value of command.CommandText at that point is "Select Year from tblTest WHERE Year = #Year"
Your instance of OleDbDataAdapter was created using two parameters query text and connection.
Dim UserQuery As New OleDbDataAdapter(command.CommandText, conn)
In this case DataAdapter doesn't know about parameters at all.
Instead use constructor with paremeter of type OleDbCommand.
Dim UserQuery As New OleDbDataAdapter(command)
In your code instance of OleDbCommand already associated with connection
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