VB.net & Access query - vb.net

Im currently doing a vb.net project for college and want to create a new access record using textboxes, masked textboxes and richtextboxes using the vb gui. However I keep getting this exception:
"An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error in INSERT INTO statement."
Here is my code which is working on other forms
Private Sub btnSaveNew_Click(sender As Object, e As EventArgs) Handles btnSaveNew.Click
Dim objrow As DataRow
objrow = objDataSet.Tables("tblEngineersReport").NewRow
objrow.Item("To") = txtTo.Text
objrow.Item("Date_Carried_Out") = txtCompletedDate.Text
objrow.Item("Description_Of_Work") = txtWorkDescription.Text
objrow.Item("Comment") = txtComment.Text
objrow.Item("Quantity1") = txtQuantity1.Text
objrow.Item("Quantity2") = txtQuantity2.Text
objrow.Item("Quantity3") = txtQuantity3.Text
objrow.Item("Quantity4") = txtQuantity4.Text
objrow.Item("Item_Description1") = txtDescription.Text
objrow.Item("Item_Description2") = txtDescription2.Text
objrow.Item("Item_Description3") = txtDescription3.Text
objrow.Item("Item_Description4") = txtDescription4.Text
objrow.Item("Unit_Price1") = txtUnitPrice1.Text
objrow.Item("Unit_Price2") = txtUnitPrice2.Text
objrow.Item("Unit_Price3") = txtUnitPrice3.Text
objrow.Item("Unit_Price4") = txtUnitPrice4.Text
objrow.Item("Rate1") = txtRate1.Text
objrow.Item("Rate2") = txtRate2.Text
objrow.Item("Rate3") = txtRate3.Text
objrow.Item("Labour1") = txtDescription5.Text
objrow.Item("Labour2") = txtDescription6.Text
objrow.Item("Labour3") = txtDescription7.Text
objrow.Item("Hours_Worked1") = txtHours1.Text
objrow.Item("Hours_Worked2") = txtHours2.Text
objrow.Item("Hours_Worked3") = txtHours3.Text
objDataSet.Tables("tblEngineersReport").Rows.Add(objrow)
objEngineerDA.Update(objDataSet, "tblEngineersReport")
Retrieve()
MessageBox.Show("new record added")
cboJobID.Enabled = True
End Sub
the Quanity textboxes down to the hours worked are contained within a table layout panel and am just wondering would this have anything to do with the record not saving?

Looking at the names of your columns I could notice that you have a column named TO. This is a reserved keyword in MS-Access and thus the autogenerated queries for your adapter will have a syntax error if you don't tell to your OleDbCommandBuilder to encapsulate the column names with the appropriate QuotePrefix and QuoteSuffix string.
You need to add this code, just after the declaration and initialization of your OleDbCommandBuilder-
Dim builder = new OleDbCommandBuilder(objEngineerDA)
builder.QuotePrefix = "["
builder.QuoteSuffix = "]"

You'll need to check the INSERT statement used in the definition of your DataAdapter (objEngineerDA). The syntax of that INSERT is apparently incorrect, according to the error. Without seeing what is currently there, I cannot advise as to what is wrong with it.

Related

Make pre-prepared sql command in libreoffice basic

I'm trying to make a prepared query based on the value in a field in my form in libreoffice basic.For this, I created a macro.
But it returns an error on the query line saying
BASIC syntax error.
Unexpected symbol: oInstruction_SQL
Sub concatMotherName
Dim oSourceDonnees As Object
Dim oConnexion As Object
Dim stSql As String
Dim oResultat As Object
oSourceDonnees = thisComponent.Parent.dataSource
oConnexion = oSourceDonnees.getConnection("","")
oInstruction_SQL = oConnexion.createStatement()
Dim valueData As String
Dim dateLabel As String
valueData = ThisComponent.Drawpage.Forms.getByName("Form").getByName("id_mother_label").getCurrentValue()
stSql = "SELECT NOM_MERE FROM ""T_MOTHER"" WHERE ""NUM_MOTHER"" = ?" _
oInstruction_SQL = = oConnection.prepareStatement(stSql)
oInstruction_SQL.setString(1, valueData)
oResultat = oInstruction_SQL.executeQuery(stSql)
If Not IsNull(oResultat) Then
oResultat.Next()
MsgBox oResultat.getString(1)
End If
End Sub
There are two syntax problems. The first is the _ after the query string, which indicates that the next line is a continuation of that one. It's not a continuation, so remove it.
The second error is on the next line: = =.
When these errors are fixed, the code compiles successfully.

vb.net form linq nullreferenceexception

I'm working on a Sindows Forms application to help keep inventory of some scanners. I'm using Linq2Sql, each table has an id column. On my repair history form. I'm trying to use the serial number from the inventory table so it goes to the database and looks up the sID from the table and it returns the correct value, but when I go to send all the entered data to the history table it gets a null reference exception.
Dim db As New DataClasses1DataContext
Dim rep As Scanner_Repair_History
Dim scan = (From Scanner_Inventory In db.Scanner_Inventories Where scannerid.Text = Scanner_Inventory.SN Select Scanner_Inventory.SID).FirstOrDefault
rep.SID = scan
rep.Date_Broken = datebroke.Value
rep.Description = description.Text
rep.Send_Date = senddate.Text
rep.Recieve_Date = recievedate.Text
rep.Cost = cost.Text
rep.PlantID = plantid.Text
rep.BID = brokenid.Text
rep.RMAnumber = rmanum.Text
db.Scanner_Repair_Histories.InsertOnSubmit(rep)
db.SubmitChanges()
is that me but you didn't instanciate your "rep" variable
You don't have a defined object for placement with a 'new' keyword but I am also curious if it is a system.type.
Update based on Jinx88909
You may be returning an entire POCO Object that may be null and have a null property. You can adjust this most times by doing a null condition if you are using .NET 4.5 and up. '?.' operator.
Dim db As New DataClasses1DataContext
'I need to be a new object and not instantiated as Nothing
Dim rep As New Scanner_Repair_History
'You have the potential for a nothing value here as 'FirstOrDefault' includes a potential Nothing'.
'I would get the entire object and then just a property of it after the fact
Dim scan = (From Scanner_Inventory In db.Scanner_Inventories Where scannerid?.Text = Scanner_Inventory?.SN Select Scanner_Inventory).FirstOrDefault?.Sid
If scan IsNot Nothing Then
rep.SID = scan 'Could you maybe want scan.Id or something similar?
rep.Date_Broken = datebroke.Value
rep.Description = description.Text
rep.Send_Date = senddate.Text
rep.Recieve_Date = recievedate.Text
rep.Cost = cost.Text
rep.PlantID = plantid.Text
rep.BID = brokenid.Text
rep.RMAnumber = rmanum.Text
db.Scanner_Repair_Histories.InsertOnSubmit(rep)
db.SubmitChanges()
Else
Console.WriteLine("I got nothing for you with the inputs you put in!")
End If

System.Data.OleDb.OleDbException

I'm trying to connect to .accdb access 2010 database.
I'm getting this:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Data type mismatch in criteria expression.
But I don't know where and what the problem is. What should I do?
This is my code:
Private Sub frm_ViewsOrder_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
cmb_order.DataSource = get_data("SELECT DISTINCT fld_order_no FROM tbl_order")
cmb_order.DisplayMember = "fld_order_no"
End Sub
Private Sub refresh_grid(orderid As String)
grd_view.DataSource = get_data("SELECT fld_product_name, fld_bil, fld_price, fld_bil * fld_price as Total FROM tbl_products, tbl_order WHERE tbl_order.fld_product_id = tbl_products.fld_product_id AND tbl_order.fld_order_no = """ & orderid & """ ")
grd_view.Columns(0).HeaderText = "Product Name"
grd_view.Columns(1).HeaderText = "Quantity"
grd_view.Columns(2).HeaderText = "Unit Price (RM)"
grd_view.Columns(3).HeaderText = "Amount(RM)"
grd_view.Columns(2).DefaultCellStyle.Format = "N2"
grd_view.Columns(3).DefaultCellStyle.Format = "N2"
Dim totalValue As Decimal
For Each dgvRow As DataGridViewRow In grd_view.Rows
If Not dgvRow.IsNewRow Then
totalValue += CDec(dgvRow.Cells(3).Value)
End If
Next
txt_total.Text = String.Format("{0:n2}", totalValue)
End Sub
In your SQL I would check that "fld_bil" and "fld_price" are both numeric (like you're not multiplying two string's that have numbers in them together). I would also make sure that "fld_order_no" and your local variable "ordered" are numeric. The type exception from OLEDB makes me think it's a conversion error in the SQL.
Also, you probably want to parameterize your query to prevent SQL injection exploits. It's very easy to do. In your command object (which is presumably in your get_data method) you would want to do something like this:
cmd.CommandText = "SELECT fld_product_name, fld_bil, fld_price, fld_bil * fld_price as Total FROM tbl_products, tbl_order WHERE tbl_order.fld_product_id = tbl_products.fld_product_id AND tbl_order.fld_order_no = #orderid"
' ordered being your local variable
cmd.Parameters.AddWithValue("#orderid", orderid)
This will help prevent anyone from tacting on SQL to the end of your query. Here is a link with a more in depth parameterized query example in VB.Net:
http://www.blakepell.com/2012-02-28-vbnet-parameterized-query-example-and-why-you-should-care

Vb.net Code syntax error

I have following vb.net code and i am getting syntax error in it
Update
Protected Sub OpenLogin_Click(ByVal src As Object, ByVal e As CommandEventArgs)
Dim StrUri As String = e.CommandArgument.ToString()
Dim openid As New OpenIdRelyingParty()
Dim b = New UriBuilder(Request.Url)
With Key
.Query = ""
End With
'var b = new UriBuilder(Request.Url) { Query = "" };
Dim req = openid.CreateRequest(StrUri)
Dim fetchRequest = New FetchRequest()
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email)
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.First)
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last)
req.AddExtension(fetchRequest)
req.RedirectToProvider()
End Sub
Now the error in code is "Key is Not declared" What should i do now for this
Two problems:
The Key reserved word is only to be used when identifying a multi-part key for grouping using Enumerable.GroupBy. It is not required for setting object properties inline with their constructor.
You are experiencing a problem whereby you have separated the With decorator onto a new line, which is syntactically incorrect because you are now treating it as a With block, which means that every dot access will target the variable immediately following the With statement. You need to use a line continuation character or put With on the same line as the object constructor:
Ex 1
Dim b = New UriBuilder(Request.Url) With {
.Query = ""
}
Ex 2
Dim b = New UriBuilder(Request.Url) _
With { .Query = "" }
EDIT:
You cannot use this syntax with a Visual Studio 2005/.NET 2.0 project. Just construct the object then initialize the property:
Dim b As New UriBuilder(Request.Url)
b.Query = ""
AFAIK, you don't need the curly braces.
With Something
.Property1 = True
.Property2 = "Inactive"
' And so on
End With
UPDATE
With Key
.Query = ""
End With
Why do you need a With clause here anyway ? The above is syntactically equivalent to
Key.Query = ""
Declare the Key variable or else remove it from your code.

Where is my mistake?

I have table which is connected to datagridview and I would like to enter new data by using text boxes. I have following code but it gives me error. Will be appreciated if you help me. Error Message is : Use the "new" keyword to create an object instance
Dim meter As DataTable = Me.DataSet1.Tables.Item("tblmeters")
Dim row As DataRow = meter.NewRow()
row.Item("No") = Me.txtno.Text
row.Item("Turnover") = Me.txtturnover.Text
row.Item("Total Win") = Me.txttotalwin.Text
row.Item("Games Played") = Me.txtgamesplayed.Text
row.Item("Credit In") = Me.txtcreditin.Text
row.Item("Bill In") = Me.txtbillin.Text
row.Item("Hand Pay") = Me.txthandpay.Text
row.Item("Date") = DateTime.Today.ToShortDateString
meter.Rows.Add(row)
Me.TblMeterTableAdapter.Update(Me.DataSet1.tblMeter)
meter.AcceptChanges()
Looks like Me.DataSet1.Tables.Item("tblmeters") returns Nothing. Make sure that DataSet1 indeed contains table tblmeters.