DBNull -Conversion Error - sql

I am having below error
Conversion from type 'DBNull' to type 'Integer' is not valid. When submit the form above error is showing Is it because of any fields in database having NULL VALUE or what could be the real reason.
When I click save
Dim intresult As String
Dim objParam As OleDbParameter() = {objDA.OutputParam("#Next_DocumentNo", OleDbType.VarChar, 20), _
objDA.InputParam("#Dtype", OleDbType.VarChar, 10, "D"), _
objDA.InputParam("#MID", OleDbType.VarChar, 20, Session("Mid"))}
intresult = objDA.ExecSP("dbo.GetNextDocNo", objParam)
If intresult = 1 Then
tNextDocNo = objDA.varOutputRet
Else
Exit Sub
End If
vDocType = "D"
vAllocID = "501"
vDummy = " "
vDummyBuyer = "NEX"
vRemarks = Replace(Replace(Me.TextRemark.Text, "'", "''"), vbCrLf, "")
strSQL = "INSERT INTO dbo.Hder (Document_Type, Document_No, Document_Date, Trans_Type, Type_Desc, V_Type, " & _
"Mid,Total_Amount, Total_Qty,Prepared_By,Remarks) " & _
"VALUES ('" & vDocType & "', '" & tNextDocNo & "', '" & Me.TextDate.Text & "', 'D', 'gift IN', 'GIFT', " & _
"'" & Mid & "', " & CDbl(Me.txtGrandTotal.Text) & ", " & CDbl(Me.txtTotalQty.Text) & ", " & _
"'" & GCurrentUserName & "', '" & vRemarks & "')"
intresult = objDA.ExecSP(strSQL, "Trans")
varOutputRet = CType(objCmd.Parameters(0).Value, Integer)
Error is highlighted in the below code in another form when I submit the above code
varOutputRet = CType(objCmd.Parameters(0).Value, Integer)

Check for DBNull before you cast:
varOutputRet = CInt(If(IsDBNull(objCmd.Parameters(0).Value), 0, objCmd.Parameters(0).Value))

Related

Need Help for Updating database in vb.net

Someone knows why I got an exception when the code running at cmd.ExecuteNonQuery()? when I update Date, it runs perfectly but when I update the Finish date, I got that error.
This is the code
Call connection()
If txt_UpCom.Text = "" Or cbCom.SelectedItem = "" Then
If txt_ComNew.Enabled = True Then
MessageBox.Show("Please fill the entire data!")
End If
Else
Try
Dim str As String
If cbCom.SelectedItem = "Date" Or cbCom.SelectedItem = "Finish Date" Then
Dim comdate As String = dateCom.Value.ToString("yyyy-MM-dd")
str = "UPDATE complain SET " & cbCom.SelectedItem & "= '" & comdate & "' WHERE ComplainID = '" & txt_UpCom.Text & "'"
Else
str = "UPDATE complain SET " & cbCom.SelectedItem & " = '" & txt_ComNew.Text & "' WHERE ComplainID = '" & txt_UpCom.Text & "'"
End If
cmd = New MySql.Data.MySqlClient.MySqlCommand(str, conn)
cmd.ExecuteNonQuery()
msgBoxSuccess.ShowDialog()
conn.Close()
Catch ex As Exception
MessageBox.Show("Unable to Update")
End Try
End If
This is the table in database
As #Jacek Wróbel mentioned in the comments, you should keep the column names between [] (square brackets) or "" (double quots). The same thing goes for table names (or any other SQL objects for that matter).
Long story short, change this part of your code:
If cbCom.SelectedItem = "Date" Or cbCom.SelectedItem = "Finish Date" Then
Dim comdate As String = dateCom.Value.ToString("yyyy-MM-dd")
str = "UPDATE complain SET " & cbCom.SelectedItem & "= '" & comdate & "' WHERE ComplainID = '" & txt_UpCom.Text & "'"
Else
str = "UPDATE complain SET " & cbCom.SelectedItem & " = '" & txt_ComNew.Text & "' WHERE ComplainID = '" & txt_UpCom.Text & "'"
End If
to this:
If cbCom.SelectedItem = "Date" Or cbCom.SelectedItem = "Finish Date" Then
Dim comdate As String = dateCom.Value.ToString("yyyy-MM-dd")
str = "UPDATE `complain` SET `" & cbCom.SelectedItem & "` = '" & comdate & "' WHERE `ComplainID` = '" & txt_UpCom.Text & "'"
Else
str = "UPDATE `complain` SET `" & cbCom.SelectedItem & "` = '" & txt_ComNew.Text & "' WHERE `ComplainID` = '" & txt_UpCom.Text & "'"
End If
Note: I prefer to keep things consistant, so I added [] to each object whether it contains spaces or not.

want to update record if exists and insert if not exists

want to update record if exists and insert if not exists into vsolv_trn_tsalesregdump Is tsalesregdump_name is unique in table vsolv_trn_tsalesregdump
when i click check box that particular row should be check on other table and how to use it for loop in form loop i can use the "tsalesdump_date,tsalesdump_name,executivename_executive" this three if the value is same its go to update and otherwise its not to same its move on insert how can i write it can any 1help me
if i have use two table one temp and other 1 is orginal\ temp table =vsolv_tmp_tsalesdump orginal table=vsolv_trn_tsalesregdump.
if already i hav save the data in orginal table,again if i hav assing data for temp table and view in radgrid if select and submit the button its go to check on orginal table if the value is already there its update it otherwise insert how can use it
Protected Sub btn_Submit_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btn_Submit.Click
lblerrmsg.Text = ""
Dim chk As CheckBox
Dim lbtn As LinkButton
Dim Res As Long
Dim lobjrow As DataRow
Dim lObjErrTable As New DataTable
Dim a As Integer = 0
Dim dtcarbooking As New DataTable
Dim dtDumpBooking As New DataTable
Dim lsRefid As String = String.Empty
Dim dtdumpsample As New DataTable
Dim name As String = String.Empty
If Check_Validation() = True Then
Exit Sub
End If
Gobjdbconn.OpenConn()
lObjErrTable = Error_TabelFill()
For i As Integer = 0 To GVUpload.Items.Count - 1
chk = GVUpload.Items(i).FindControl("chkupload")
If chk.Checked = True Then
lsRefid = GVUpload.Items(i).GetDataKeyValue("tsalesdump_gid").ToString()
MsSql = ""
MsSql &= "Select tsalesdump_gid,tsalesdump_date,tsalesdump_name,executivename_executive,tsalesdump_vch_no,tsalesdump_debit,tsalesdump_credit"
MsSql &= " from vsolv_tmp_tsalesdump as a"
MsSql &= " left join vsolv_trn_executivename as b on a.tsalesdump_name = b.executivename_particulars"
MsSql &= " where tsalesdump_gid = '" & lsRefid & "' and tsalesdump_isremoved = 'N'"
dtDumpBooking = Gobjdbconn.GetDataTable(MsSql)
MsSql = ""
MsSql &= "Insert into vsolv_trn_tsalesregdump(tsalesregdump_date,tsalesregdump_name,tsalesregdump_executive,tsalesregdump_vch_no"
MsSql &= " ,tsalesregdump_debit,tsalesregdump_credit,tsalesregdump_importby)"
MsSql &= " Values ('" & Format(CDate(dtDumpBooking.Rows(0).Item("tsalesdump_date")), "yyyy-MMM-dd").ToString() & "'"
MsSql &= ",'" & dtDumpBooking.Rows(0).Item("tsalesdump_name").ToString() & "'"
MsSql &= ",'" & dtDumpBooking.Rows(0).Item("executivename_executive").ToString() & "'"
MsSql &= " ,'" & dtDumpBooking.Rows(0).Item("tsalesdump_vch_no").ToString() & "'"
MsSql &= " ,'" & dtDumpBooking.Rows(0).Item("tsalesdump_debit").ToString() & "','" & dtDumpBooking.Rows(0).Item("tsalesdump_credit").ToString() & "','SIVA')"
MnResult = Gobjdbconn.ExecuteNonQuerySQL(MsSql)
If MnResult = 1 Then
MsSql = ""
MsSql &= " Delete from vsolv_tmp_tsalesdump where tsalesdump_gid = '" & lsRefid & "'"
Gobjdbconn.ExecuteNonQuerySQL(MsSql)
Else
lobjrow = lObjErrTable.NewRow()
a = a + 1
lobjrow("Sno") = a
lobjrow("Booking Ref No") = dtcarbooking.Rows(0).Item("tsalesregdump_name").ToString
lobjrow("Description") = "Duplicate Record"
lObjErrTable.Rows.Add(lobjrow)
End If
End If
Next
POPSummary()
If Not lObjErrTable Is Nothing Then
If lObjErrTable.Rows.Count > 0 Then
Call Pop_Data(lObjErrTable)
End If
End If
End Sub
If you want to update record if already exists else insert in SQL then you can achieve by following: You need to change MsSql string for Insert command
MsSql = "" + _
"IF EXISTS(Select tsalesregdump_name From vsolv_trn_tsalesregdump Where tsalesregdump_name = '" & dtDumpBooking.Rows(0).Item("tsalesdump_name").ToString() & "') " + _
"BEGIN " + _
" Update vsolv_trn_tsalesregdump " + _
" Set tsalesregdump_date = '" & Format(CDate(dtDumpBooking.Rows(0).Item("tsalesdump_date")), "yyyy-MMM-dd").ToString() & "' " + _
" ,tsalesregdump_executive = '" & dtDumpBooking.Rows(0).Item("executivename_executive").ToString() & "' " + _
" ,tsalesregdump_vch_no = '" & dtDumpBooking.Rows(0).Item("tsalesdump_vch_no").ToString() & "' " + _
" ,tsalesregdump_debit = '" & dtDumpBooking.Rows(0).Item("tsalesdump_debit").ToString() & "' " + _
" ,tsalesregdump_credit = '" & dtDumpBooking.Rows(0).Item("tsalesdump_credit").ToString() & "' " + _
" ,tsalesregdump_importby = 'SIVA' " + _
" Where tsalesregdump_name = '" & dtDumpBooking.Rows(0).Item("tsalesdump_name").ToString() & "' " + _
"END " + _
"ELSE " + _
"BEGIN " + _
" Insert into vsolv_trn_tsalesregdump(tsalesregdump_date,tsalesregdump_name,tsalesregdump_executive,tsalesregdump_vch_no " + _
" ,tsalesregdump_debit,tsalesregdump_credit,tsalesregdump_importby) " + _
" Values ('" & Format(CDate(dtDumpBooking.Rows(0).Item("tsalesdump_date")), "yyyy-MMM-dd").ToString() & "' " + _
" ,'" & dtDumpBooking.Rows(0).Item("tsalesdump_name").ToString() & "' " + _
" ,'" & dtDumpBooking.Rows(0).Item("executivename_executive").ToString() & "' " + _
" ,'" & dtDumpBooking.Rows(0).Item("tsalesdump_vch_no").ToString() & "' " + _
" ,'" & dtDumpBooking.Rows(0).Item("tsalesdump_debit").ToString() & "','" & dtDumpBooking.Rows(0).Item("tsalesdump_credit").ToString() & "','SIVA') " + _
"END "
MnResult = Gobjdbconn.ExecuteNonQuerySQL(MsSql)
I am assuming here that tsalesregdump_name is unique.

datatype mismatch in criteria expression vb2010 edit button

I'm getting the error
datatype mismatch in criteria expression vb.net edit button
when I click the edit button on my vb2010 project. Adding and search button works fine but not on edit button.
Here is my code:
Private Sub BtnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnEdit.Click
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=D:\pcInventory.accdb"
myConnection = New OleDbConnection
OpenStr = "Has Open Office"
If TbPCnum.Text = "" Then
MsgBox("Please select data.")
Else
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "update [pctable] set [Person Incharge] = '" & TbPI.Text & "', [DeptSection] = '" & TbDS.Text & "', [Workgroup] = '" & TbWG.Text & "', [Network ID] = '" & TbNI.Text & "', [OS] = '" & TbOS.Text & "', [Processor] = '" & TbProcessor.Text & "', [MOBO] = '" & TbMB.Text & "', [Memory] = '" & TbRAM.Text & "', [HDD] = '" & TbHDD.Text & "', [Product Key] = '" & TbKey.Text & "', [MS Office] = '" & CbMS.SelectedValue & "', [Open Office] = '" & tbOO.Text & "', [Anti Virus] = '" & TbAV.Text & "', [Monitor] = '" & TbMonitor.Text & "', [Email Address] = '" & TbEadd.Text & "', [Date Purchased] = '" & TbDP.Text & "', [Machine Type] = '" & comboMT.SelectedValue & "', [Remarks] = '" & TbRM.Text & "', [Password] = '" & TbPW.Text & "' Where [PCNumber] = '" & TbPCnum.Text & "'"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
TbPCnum.Clear()
TbPI.Clear()
TbDS.Clear()
TbWG.Clear()
TbNI.Clear()
TbOS.Clear()
TbProcessor.Clear()
TbMB.Clear()
TbRAM.Clear()
TbHDD.Clear()
TbKey.Clear()
tbOO.Clear()
TbAV.Clear()
TbMonitor.Clear()
TbEadd.Clear()
TbDP.Clear()
TbRM.Clear()
TbPW.Clear()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Sub
I suspect that it may be your query string. You sending a string/text instead of an int/number for example.
check through it and make sure that the database column type matches the data you sending through with the query.
Remove the single quotation marks if you sending int/numeric values.

How to solve issue with ExecuteNonQuery in VB.net

This is my code for connection in form.load
cnn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\DatabaseCasanova.mdb"
cnn.Open()
And this is my SQL statement:
If ClientNoTextBox.Text <> "" And FirstNameTextBox.Text <> "" And LastNameTextBox.Text <> "" And AddressTextBox.Text <> "" And ContactNumberTextBox.Text <> "" And ProductCodeTextBox.Text <> "" And ProductNameTextBox.Text <> "" And UnitTextBox.Text <> "" And PriceTextBox.Text <> "" And TotalPriceTextBox.Text <> "" Then
cmdinsert.CommandText = "INSERT INTO Orders(InvoiceNumber, ClientNo, FirstName, LastName, Address, ContactNumber, ProductCode, ProductName, Unit, Quantity, Price, TotalPrice, [DatePurchase], [DateToDeliver]) VALUES (" & Label4.Text & ", " & ClientNoTextBox.Text & ", '" & FirstNameTextBox.Text & "', '" & LastNameTextBox.Text & "', '" & AddressTextBox.Text & "', " & ContactNumberTextBox.Text & ", " & ProductCodeTextBox.Text & ", '" & ProductNameTextBox.Text & "', '" & UnitTextBox.Text & "', " & PriceTextBox.Text & ", " & TotalPriceTextBox.Text & ", '" & Label2.Text & "', '" & DateToDeliverDateTimePicker.Text & "')"
cmdinsert.CommandType = CommandType.Text
cmdinsert.ExecuteNonQuery()
MsgBox("ADDED")
ProductNameTextBox.Clear()
PriceTextBox.Clear()
FirstNameTextBox.Clear()
TotalPriceTextBox.Clear()
UnitTextBox.Clear()
LastNameTextBox.Clear()
AddressTextBox.Clear()
ClientNoTextBox.Clear()
ProductCodeTextBox.Clear()
QuantityTextBox.Clear()
ContactNumberTextBox.Clear()
Else
MsgBox("Complete your Transaction")
End If
cmdinsert.Dispose()
I don't know where is the problem because I try 5x to retype the SQL statement.
MS Access is my database and VB10 program

Getting text from text boxes on tab control

I have a form with a tabcontrol in it with 4 tabpages each has it's own texboxes and comboboxes, then I have a button outside of the tabcontrol wich builds a SQL string from all the values entered in these boxes even if some are left blank, the issue is that when i press the button i get a null reference exception and even when I use Try..Catch or on error resume next the compiler refuses to create the text string.
here is the code I have:
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
If Me.BankGuidTextBox.Text = vbNullString Then
Me.BankGuidTextBox.Text = Guid.Empty.ToString
End If
If Me.BankNumTextBox.Text = vbNullString Then
Me.BankNumTextBox.Text = 0
End If
If Me.NameTextBox.Text = vbNullString Or Me.CodeTextBox.Text = vbNullString Then
GoTo outofsub
End If
Try
Dim strSQL3 As String
strSQL3 = "USE MSILHR" & vbCrLf & _
"UPDATE employee SET Code = '" & Me.CodeTextBox.Text & "', Name = '" & Me.NameTextBox.Text & "', Latinname = '" & Me.LatinNameTextBox.Text & "', Barcode = '" & Me.BarcodeTextBox.Text & "', FirstName = '" & Me.FirstNameTextBox.Text & "', LastName = '" & Me.LastNameTextBox.Text & "', idFather = '" & Me.IdFatherTextBox.Text & "', idMother = '" & Me.IdMotherTextBox.Text & "', idBirthDate = '" & Me.IdBirthDateDateTimePicker.Text & "', idBirthplace = '" & Me.IdBirthPlaceTextBox.Text & "', idSex = '" & Me.IdSexComboBox.SelectedValue & "', idMaritalstat = '" & Me.IdMaritalstatComboBox.SelectedValue & "', idSmoker = '" & Me.IdSmokerComboBox.SelectedValue & "', idMilitary = '" & Me.IdMilitaryComboBox.SelectedValue & "', idRegistry = '" & Me.IdRegistryTextBox.Text & "', idNum = '" & Me.IdNumTextBox.Text & "', idAddress = '" & Me.IdAddressTextBox.Text & "', idNationality = '" & Me.IdNationalityTextBox.Text & "', idReligion = '" & Me.IdReligionComboBox.SelectedItem & "', idTel = '" & Me.IdTelTextBox.Text & "', idMobile = '" & Me.IdMobileTextBox.Text & "', idNotes = '" & Me.IdNotesTextBox.Text & "', jStartDate = '" & Me.JStartDateDateTimePicker.Text & "', jQuitDate = '" & Me.JQuitDateDateTimePicker.Text & "', jQuitReason = '" & Me.JQuitReasonTextBox.Text & "', jSocialSec = '" & Me.JSocialSecTextBox.Text & "', jSocialdin = '" & Me.JSocialdinDateTimePicker.Text & "', jSocialdout = '" & Me.JSocialdoutDateTimePicker.Text & "', jHoliday1 = '" & Me.JHoliday1ComboBox.SelectedValue & "', jHoliday2 = '" & Me.JHoliday2ComboBox.SelectedValue & "', jEmpStat = '" & Me.JEmpStatComboBox.SelectedValue & "', jEmail = '" & Me.JEmailTextBox.Text & "', jPrevvacs = '" & Me.JPrevvacsTextBox.Text & "', jAdminvacs = '" & Me.JAdminvacsTextBox.Text & "', jHealthvacs = '" & Me.JHealthvacsTextBox.Text & "', jUnpaidvacs = '" & Me.JUnpaidvacsTextBox.Text & "', DepartmentGuid = '" & Me.DepartmentGuidComboBox.SelectedValue.ToString & "', JobTitleGuid = '" & Me.JobTitleGuidComboBox.SelectedValue.ToString & "',SalarycalctypeGuid = '" & Me.SalarycalctypeGuidComboBox.SelectedValue.ToString & "', TeamGuid = '" & Me.TeamGuidComboBox.SelectedValue.ToString & "', WorkDays = '" & Me.WorkDaysTextBox.Text & "', DaHours = '" & Me.DaHoursTextBox.Text & "', OverTimeHourPrice = '" & Me.OverTimeHourPriceTextBox.Text & "', CutSalary = '" & Me.CutSalaryTextBox.Text & "',BasicSalary = '" & Me.BasicSalaryTextBox.Text & "', SpecialSalary = '" & Me.SpecialSalaryTextBox.Text & "',CurrencyGuid = '" & Me.CurrencyGuidComboBox.SelectedValue.ToString & "', BankGuid = '" & Me.BankGuidTextBox.Text & "', BankNum = '" & Me.BankNumTextBox.Text & "', PeriodGUID = '" & Me.EmpperiodCombo.SelectedValue.ToString & "'" & vbCrLf & _
"WHERE GUID = '" & Me.GUIDTextBox.Text & "'"
'"update employee set Picturepath = (select name from types where type = '660')+'\" & Me.NameTextBox.Text & "' where code = '" & Me.CodeTextBox.Text & "' AND Name = '" & Me.NameTextBox.Text & "'"
Dim dbConnection As New SqlConnection(connectionString)
' A SqlCommand object is used to execute the SQL commands.
Dim cmd As New SqlCommand(strSQL3, dbConnection)
' Open the connection, execute the command, and close the connection.
' It is more efficient to ExecuteNonQuery when data is not being
' returned.
dbConnection.Open()
cmd.ExecuteNonQuery()
dbConnection.Close()
MessageBox.Show("Record is updated.", _
"Data Addition Status", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch sqlExc As SqlException
MessageBox.Show(sqlExc.ToString, "SQL Exception Error!", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
'Me.EmployeeTableAdapter.Fill(Me.MSILHRDataset.employee)
ResetUI()
outofsub:
MsgBox("you need to add more information!", MsgBoxStyle.Information, "Error")
End Sub
Ok new update :
I entered some data left some text boxes empty but made sure all combo boxes has values selected in them and then pressed updatebutton I got the same problem, but I redid that changed the current tab selected to any other one (from the other four) and then switched back to the previous tab, I press the button and IT WORKS!!?? it's as if the form doesn't Commit the values entered by user until focus changes or something it's crazy.
You are only catching a SqlException.
You need to also catch a general exception.
Catch sqlExc As SqlException
MessageBox.Show(sqlExc.ToString, "SQL Exception Error!", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Catch exc As Exception
MessageBox.Show(exc.ToString, "General Exception Error!", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Not sure why you are getting a null exception.
But it is not caught because it is not a SqlException.
On that String break it down do see where it is breaking.
On the surface it looks like it should work.
I suspect one of the controls is returning null rather than string.empty.