System.Data.OleDb.OleDbException - vb.net

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

Related

Linq Entity With Return Function

I have 2 tables:
Room_Type (ID_Room_Type, Name_Room_Type)
Room_Room (ID_Room_Type, Number_Room)
How to place a new column Temp in the RoomType table that will take its value as the sum of the rooms from the Room_Room table.
This code does not work :
Private Sub SimpleButton1_Click(sender As Object, e As EventArgs) Handles SimpleButton1.Click
Dim Db As New HotelEntities
Dim s = (From I In Db.Room_Type Select I.ID_Room_Type, I.Name_Room_Type, ColumnTemp = GetTotal_Room(I.ID_Room_Type)).ToList()
Me.DataGridView1.DataSource = s
End Sub
Private Function GetTotal_Room(id_room_type As Int32) As Int32
Dim Db As New HotelEntities
Return (From I In Db.Room_Room Where I.ID_Room_Type = id_room_type).Count
End Function
Message Error :LINQ to Entities does not recognize the method 'Int32
GetTotal_Room(Int32)' method, and this method cannot be translated
into a store expression.
I had a similar problem and I solved it by extracting the list first and then applying linq over it. You can try by altering your code as below.
Dim Db As New HotelEntities
Dim roomTypeList = Db.Room_Type.ToList()
Dim s = (From I In roomTypeList
Select I.ID_Room_Type, I.Name_Room_Type,
ColumnTemp = GetTotal_Room(I.ID_Room_Type)).ToList()
Me.DataGridView1.DataSource = s
Entity Framework will generate Linq query expressions to valid sql query.
As error message explain EF doesn't know how to convert your method GetTotal_Room to valid sql query.
Instead you can get required result from one query, without extra function.
From roomRoom In db.Room_Room
Join roomType In db.Room_Type On roomRoom.ID_Room_Type Equals roomType.ID_Room_Type
Select New With { roomRoom.ID_Room_Type, roomType.Name_Room_Type } Into roomtypes
Group roomtypes By roomtypes Into grouptypes
Select New With
{
Id = grouptypes.Key.ID_Room_Type,
Name = grouptypes.Key.Name_Room_Type,
Total = grouptypes.Count()
}
As additional notice, I don't know context of your application, but based on given sample, I think you can remove some prefixes and suffixes in table and column names
RoomType
Id
Name
Room
TypeId -- reference to RoomType.Id

LINQ Query in VB.net comparing integers

I am trying to write a LINQ query that compares an integer value in a database to an integer variable. This is not working. I can compare text values but comparing integers returns a null.
Private Sub txtRoomNum_TextChanged(sender As Object, e As EventArgs) Handles txtRoomNum.TextChanged
If Val(txtRoomNum.Text) > 99 Then
Dim intRoomNum As Integer
intRoomNum = Val(txtRoomNum.Text)
Dim RoomData = (From Rooms In BadermanIslandDataSet.Rooms
Where Rooms.HotelID = intHotelID).SingleOrDefault
''Where Rooms.HotelID = intHotelID And Rooms.RoomNumber = intRoomNum
Try
txtTest.Text = RoomData.RoomID
Catch ex As Exception
txtTest.Text = "null"
End Try
End If
End Sub
Change txtTest.Text = RoomData.RoomID
to Convert.ToInt32(txtTest.Text) = RoomData.RoomID)
You were comparing string and integer before
Since it's user input I would try using Integer.TryParse when getting the value from the text field. This will prevent an exception from being raised, and in the case the parse fails you can ask your user to only use a number in that field.
If Integer.TryParse(txtRoomNum.Text, intRoomNum) Then
...your logic
Else
...something to let them know to only put a number in txtRoomNum.Text
End If
Ok, I found the issue. I needed a RoomsBindingSource on the form. Once that was added it worked like a champ.

VB.net & Access query

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.

How to sort DataGridView Column by date in VB visual studio 2012?

In my DGV, I have date list in the column (1):
11-Sep-2014
11-May-2011
11-Jan-2014
11-Mar-2014
12-Sep-2010
how to get descending result like this:
11-Sep-2014
11-Mar-2014
11-Jan-2014
11-May-2011
12-Sep-2010
The Column(1) is not DateTime type but SortText type, I must set string like that. Could it sorted?
I have tried using code:
DGV.Columns(1).SortMode = DGV.Sort(DGV.Columns(1), System.ComponentModel.ListSortDirection.Descending)
but it's useless, it don't sort by date :(
this is my DGV:
Okeh, this is my DGV code in brief:
Imports System.Data.OleDb
Public Class LapTransaksiSimpanan
Public Sub Koneksi()
str = "provider=microsoft.jet.oledb.4.0;data source=dbkoperasi.mdb"
Conn = New OleDbConnection(str)
If Conn.State = ConnectionState.Closed Then
Conn.Open()
End If
End Sub
Sub TampilGrid()
da = New OleDbDataAdapter("select * from LapTransaksiSimpanan", Conn)
ds = New DataSet
da.Fill(ds, "LapTransaksiSimpanan")
DGV.DataSource = ds.Tables("LapTransaksiSimpanan")
'on the below I wanna to sort the column, my code below is useless :(
DGV.Sort(DGV.Columns(1), System.ComponentModel.ListSortDirection.Descending)
DGV.Columns("ID_Simpanan").Width = 120
DGV.Columns("NAK").Width = 37
DGV.Columns("Tanggal").Width = 75
DGV.Columns("Jumlah").Width = 110
End Sub
Private Sub Setoran_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Call Koneksi()
Call TampilGrid()
End Sub
End Class
There's a difference between storing and displaying data.
You need to change you database table schema. The Tanggal column should be of type date or datetime. When you've fixed this, it's trivial to display dates using a custom format:
Me.DGV.Columns("Tanggal").DefaultCellStyle.Format = "dd-MMM-yyyy"
If you for some reason cannot change the schema, then you need to create a custom comparer by implementing IComparer. There's an example at the bottom of this MSDN page.
Dim tnd As Date
For Me.i = 0 To X1.RowCount - 2
tnd = X1.Item(1, i).Value
X1.Item(6, i).Value = tnd.ToOADate.ToString
Next
X1 is DataGridView
Column 1 would have your date ex 5/4/1987
Column 6 would be calculated as MS date number in integer and must be converted to string.
Make sure X1 grid is Sort enabled
Now simply click on Column 6 header to sort.
Hope that works.

The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type

Please help me When i execute this linq to sql command its given an error "The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type."
0 Records in my Commotidy Table
I want generate manual number and get the last CommodityCode
My Code as follow,
Dim QRecordCount = From RC In cntxtCommodity.CommodityMasters _
Where RC.CommodityCode <> 0 _
Select RC.CommodityCode
LastCommodityCode = QRecordCount.Max() + 1
VB.NET 2008
Suhaib
I've tried to replicate your code with this example:
Module Module1
Sub Main()
Dim cntxtCommodity As New List(Of CommodityMasters)
cntxtCommodity.Add(New CommodityMasters With {.CommodityCode = 34})
cntxtCommodity.Add(New CommodityMasters With {.CommodityCode = 1})
cntxtCommodity.Add(New CommodityMasters With {.CommodityCode = 234})
cntxtCommodity.Add(New CommodityMasters())
Dim LastCommodityCode = cntxtCommodity.Where(Function(rc) rc.CommodityCode.HasValue AndAlso rc.CommodityCode > 0).Max(Function(rc) rc.CommodityCode)
End Sub
End Module
Public Class CommodityMasters
Public CommodityCode As Nullable(Of Integer)
End Class
Basically, the above is supposed to deal with nullable integers (CommodityCode) which should stop you getting exceptions on that part. I'm not 100% sure if it solves all your problems though, with no records in the database. Try it.