sql,vb error "no row at position 0" - sql

I get the message "there is no row at position 0" in the form with the following code:
Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
Dim i As Integer
Dim xid As Integer
Dim xQTY(0) As Integer
Dim xQTY_ID(0) As Integer
Dim xCount As Integer
Dim xCounter_ID(0) As Integer
'Dim sqlstrx(5) As String
xid = 0
**If lstitems.Items.Count > 0 Then**
If Split(Me.Text, " - ")(1) = "Add" Then
sqlSTR = "INSERT INTO orders (CustID, Cust_Name, order_date) " & _
"VALUES (" & txtcustid.Text & ", " _
& "'" & txtcustname.Text & "', " _
& "'" & Format(dttoday.Value, "MM/dd/yyyy") & "')"
ExecuteSQLQuery(sqlSTR)
sqlSTR = "SELECT * FROM orders ORDER BY order_no DESC"
ExecuteSQLQuery(sqlSTR)
xid = sqlDT.Rows(0)("order_no")
For i = 0 To lstitems.Items.Count - 1
sqlSTR = "INSERT INTO orders_detail (order_no, idDrug, DrugName, Unit_Cost, qty, totalcost) " & _
"VALUES (" & xid & ", " _
& lstitems.Items(i).Text & ", " _
& "'" & lstitems.Items(i).SubItems(1).Text & "', " _
& "'" & lstitems.Items(i).SubItems(2).Text & "', " _
& lstitems.Items(i).SubItems(3).Text & ", " _
& lstitems.Items(i).SubItems(4).Text & ", " _
& lstitems.Items(i).SubItems(5).Text & ")"
ExecuteSQLQuery(sqlSTR)
Error highlights the bold line.

your code missing fill for your dataTable
Try this :
Dim sqlAdapter As New SqlDataAdapter(sqlSTR, yourconnctionstring)
sqlAdapter.Fill(sqlDT)
If sqlDT.Rows.Count > 0 Then
xid = sqlDT.Rows(0)("order_no")
End If

Try like this
Dim sqlAdapter As New SqlDataAdapter(sqlSTR, yourconnctionstring)
sqlAdapter.Fill(sqlDT)
If sqlDT.Rows.Count > 0 Then
xid = sqlDT.Rows(0)("order_no")
End If
'write your code here.....

Related

Trying to upsize from Access tables to SQL Server linked tables. Code works fine with Access but gives a "ODBC call failed 3146" when connected to SQL

Public Sub UpdateTermFeedbackAddlReqt(ByVal runid As Integer, ByVal BHTerm As String, ByVal username As String, ByVal currtime As Double)
Dim db As DAO.Database
Dim rs As DAO.Recordset
DoCmd.SetWarnings False
Set db = CurrentDb
sql = "SELECT tbl_SCG_ExpectedTraffic.BHTerm, Sum(tbl_SCG_ExpectedTraffic.CurrSent2) AS SumOfCurrSent2, iif(Sum([CurrSent2]) = 0, 0, Sum([Accepted])/Sum([CurrSent2])) AS [Term Accept Rate], Sum(tbl_SCG_ExpectedTraffic.Accepted) AS SumOfAccepted, Sum(tbl_SCG_ExpectedTraffic.Rejected) AS SumOfRejected, Sum(tbl_SCG_ExpectedTraffic.Modified) AS SumOfModified, Sum(tbl_SCG_ExpectedTraffic.CurrCalledin) AS SumOfCalledin, Sum([ExpTotal])-Sum([CurrSent2]) AS [Need to Send]" & _
" FROM tbl_SCG_ExpectedTraffic" & _
" GROUP BY Date(), tbl_SCG_ExpectedTraffic.BHTerm, tbl_SCG_ExpectedTraffic.OptRunID" & _
" HAVING (((tbl_SCG_ExpectedTraffic.OptRunID)=" & runid & ") And BHTerm= """ & BHTerm & """);"
Set rs = db.OpenRecordset(sql, dbOpenDynaset, dbSeeChanges)
DoCmd.RunSQL ("Update tbl_SCG_TerminalFeedback set [CurrentSend2] = " & rs![SumOfCurrSent2] & ", [Term Accept Rate] =" & rs![Term Accept Rate] & ", Accepted= " & rs![SumOfAccepted] & ", Rejected = " & rs![SumOfRejected] & ", Modified =" & rs![SumOfModified] & ", Calledin = " & rs![SumOfCalledin] & ", AddlReqst =" & rs![Need To Send] & _
",[Last Update User] =""" & username & """, [Last Update Time]= " & currtime & " , HrDiff = iif( isnull(DLookup(""SubmissionDT"", ""tbl_SCG_OptRunSummary"", ""OptRunID = " & runid & """)), 0, Round((" & currtime & " - DLookup(""SubmissionDT"", ""tbl_SCG_OptRunSummary"", ""OptRunID =" & runid & """)) * 24, 1))" & _
" where OptRunID = " & runid & " And Term = """ & BHTerm & """")
DoCmd.SetWarnings True
rs.Close
db.Close
End Sub

i want to make i as textbox and take data to fill tabel lab.work vb.net

Private Sub Button19_Click(sender As Object, e As EventArgs) Handles Button19.Click
load_analyzes_details_cbc()
Dim salesId, analyzess_id As Integer
Dim rresult As Integer
Dim cmdInsert As New SqlCommand()
Dim cmd As New SqlCommand("Select *from analyzes_details where analyzess_id='1'", connSQLServer)
connSQLServer.Open()
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt_analyzes_details_cbc)
For Each row In dt_analyzes_details_cbc.Rows
salesId = Convert.ToInt32(row("details_id").ToString())
analyzess_id = Convert.ToInt32(row("analyzess_id").ToString())
For i As Integer = 0 To TextBox - 1
rresult = Convert.ToInt32(Val(i).ToString())
cmdInsert.CommandText = "Insert into lab_work(sales_id,sub_id,analyzesss_id,result) values(" & Label1.Text & "," & salesId & "," & analyzess_id & "," & rresult & ")"
cmdInsert.Connection = connSQLServer
cmdInsert.ExecuteNonQuery()
Next
Next
'Next
cmd.Dispose()
connSQLServer.Close()
load_lab_work()
End Sub
Please check your code..
cmdInsert.CommandText = "Insert into lab_work(sales_id,sub_id,analyzesss_id,result) values(" & Label1.Text & "," & salesId & "," & analyzess_id & "," & rresult & ")"
".text" Missing in textbox id
Your code will be
cmdInsert.CommandText = "Insert into lab_work(sales_id,sub_id,analyzesss_id,result) values(" & Label1.Text & "," & salesId.Text & "," & analyzess_id.Text & "," & rresult.Text & ")"

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.

syntax error insert into statement vb.net

pls help solve me this question.. im very new to this
i can't add new employee to the table employee.. whenever i try to add it shows syntax error insert into statement
Public Class AddNewEmployee
Dim dr As OleDbDataReader
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim conn As New OleDbConnection(My.Settings.rayshadatabaseConnectionString)
Dim cmd As OleDbCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
conn.Open()
Try
Dim str As String = "INSERT INTO employee" _
& "(Employee Name, IC Number, HP Number, Address)" _
& " Values (" _
& "'" & txtEmployeeName.Text & "', " _
& "'" & txtIC_Number.Text & "'," _
& "'" & txtHP_Number.Text & "'," _
& "'" & txtAddress.Text & "')"
cmd = New OleDbCommand(str, conn)
Dim i As Integer = cmd.ExecuteNonQuery()
If i > 0 Then
MessageBox.Show("Record Succesfully added.", "Process Completed", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show("Adding failed!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Close()
cmd.Dispose()
End Try
frmEmployee.loadR()
Me.Close()
End Sub
End Class
Replace this,
Dim str As String = "INSERT INTO employee" _
& "(Employee Name, IC Number, HP Number, Address)" _
& " Values (" _
& "'" & txtEmployeeName.Text & "', " _
& "'" & txtIC_Number.Text & "'," _
& "'" & txtHP_Number.Text & "'," _
& "'" & txtAddress.Text & "')"
with this,
Dim str As String = "INSERT INTO employee" _
& "([Employee Name], [IC Number], [HP Number], [Address])" _
& " Values (" _
& "'" & txtEmployeeName.Text & "', " _
& "'" & txtIC_Number.Text & "'," _
& "'" & txtHP_Number.Text & "'," _
& "'" & txtAddress.Text & "')"
Thanks
Manoj

How to populate faster in datagridview in vb.net

This is my code for populating the datagridview:
Public Sub generate_list_ftMK(ByVal clbBranch As CheckedListBox, ByVal dtpSDate As DateTimePicker, ByVal dtpEDate As DateTimePicker, ByVal dvList As DataGridView)
Dim ds As DataSet = New DataSet()
Dim da As MySqlDataAdapter
Dim strQ As String = String.Empty
Dim strQ1 As String = String.Empty
Dim colItemCode As String = String.Empty
Dim colReg_Pri As String = String.Empty
Dim colXL_Pri As String = String.Empty
Dim colDel_Date As String = String.Empty
Dim colLabel As String = String.Empty
Dim colDays As String = String.Empty
Dim PCT As String = String.Empty
Try
If con.State = ConnectionState.Open Then con.Close()
con.Open()
'clear the dataset
ds.Tables.Clear()
'loop for all branches
For i = 0 To clbBranch.CheckedItems.Count - 1
Application.DoEvents()
'get the Branch Code
chkBranch = clbBranch.CheckedItems(i).ToString
'select item code and price where JO_TYPE is JO
strQ = "select " & _
"CONCAT(a.STYLE_CODE, '-', LPAD((a.JO_NO), 4, '0'), '-', d.LINE_NO) as Item_Code, " & _
"DATE_FORMAT(c.DEL_DATE, '%Y-%m-%d') as DEL_DATE, " & _
"d.REG_PRI as Reg_Price, " & _
"d.XL_PRI as XL_Price, " & _
"a.LABEL_CODE, " & _
"a.STYLE_CODE, " & _
"LPAD((a.JO_NO), 4, '0')," & _
"d.LINE_NO, " & _
"DATEDIFF('" & Format(Date.Now, "yyyy-MM-dd") & "',DATE_FORMAT(c.DEL_DATE, '%Y-%m-%d')) as Days " & _
"from " & _
"jo_hdr as a " & _
"inner join " & _
"branch as b ON a.BRNCH_CODE = b.BRNCH_CODE " & _
"inner join " & _
"dr_hdr as c ON c.TRAN_REF = a.TRAN_NO " & _
"inner join " & _
"dr_det as d ON d.DR_NO = c.DR_NO " & _
"where " & _
"c.DEL_DATE BETWEEN '" & dtpSDate.Text & "' AND '" & dtpEDate.Text & "' " & _
"and a.LABEL_CODE = '" & FtMK_Code & "' " & _
"and a.BRNCH_CODE = '" & chkBranch & "' " & _
"and SUBSTRING(d.REG_PRI,LENGTH(d.REG_PRI) - 1,2) = 75 " & _
"and SUBSTRING(d.REG_PRI,LENGTH(d.XL_PRI) - 1,2) = 75 "
cmd = New MySqlCommand(strQ, con)
da = New MySqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "tblJO")
For r = 0 To ds.Tables("tblJO").Rows.Count - 1
Application.DoEvents()
colItemCode = ds.Tables("tblJO").Rows(r)(0).ToString
colDel_Date = ds.Tables("tblJO").Rows(r)(1).ToString
colReg_pri = ds.Tables("tblJO").Rows(r)(2).ToString
colXL_pri = ds.Tables("tblJO").Rows(r)(3).ToString
colLabel = ds.Tables("tblJO").Rows(r)(4).ToString
sumStyle = ds.Tables("tblJO").Rows(r)(5).ToString
sumJO = ds.Tables("tblJO").Rows(r)(6).ToString
sumNo = ds.Tables("tblJO").Rows(r)(7).ToString
colDays = ds.Tables("tblJO").Rows(r)(8).ToString
'for the number to decimal
colReg_pri = FormatNumber(colReg_pri, 2)
colXL_pri = FormatNumber(colXL_pri, 2)
'get the total quantity and the branch quantity
get_TotalQty_and_BranchQty()
'if the branch quantity is zero
If branchQty = 0 Then
PCT = "N\A"
Else
'compute the percent sold
PCT = totalQty
End If
dvList.Rows.Add(False, colItemCode, PCT, colDel_Date, Format(Date.Now, "yyyy-MM-dd"), colDays, _
colReg_Pri, colXL_Pri, colLabel, "JO", dtpSDate.Text, dtpEDate.Text, _
clbBranch.CheckedItems(i).ToString, mkType)
Next
Next
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
I have use indexes in my tables, and also add application.doevents. Is there anything I could do to make the populating in the datagridview faster with this code? I'm trying to search about making the datagridview doublebuffered because I read it online that I will make the datagridview faster but I have no idea how to use it.
Any help will be appreciated, Thank you.
Your issue is using
Application.DoEvents
I'm not going to get into the details of why this is bad practice, try using a Background Worker instead.