**Hi, i've a problem to load data from SQL in my MSHFlexGrid. This is my code:
Option Explicit
Dim rs As Recordset
Private Sub btnEmpieza_Click()
rs.Open "SELECT CorridaVigenciaEncabezado.CVE_Titulo, CorridaVigenciaEncabezado.CVE_Mail " _
& "FROM CorridaVigenciaEncabezado INNER JOIN Usuarios " _
& "ON CorridaVigenciaEncabezado.USU_IdSolicitado = Usuarios.Codigo " _
& "INNER JOIN Solicitud on CorridaVigenciaEncabezado.CVE_Titulo = Solicitud.ANTITSOL " _
& "WHERE Solicitud.ANDNICLI =19002108 ", Cn, adOpenKeyset, adLockReadOnly
Grilla
rs.Close
End Sub
Private Sub Form_Load()
Set rs = New Recordset
rs.CursorLocation = adUseServer
End Sub
Private Sub Estructura()
GrillaDatos.Cols = 2
GrillaDatos.TextMatrix(0, 1) = "Título"
GrillaDatos.TextMatrix(0, 2) = "Mail"
GrillaDatos.ColWidth(0) = 1000
GrillaDatos.ColWidth(1) = 1000
GrillaDatos.ColAlignment(0) = 4
GrillaDatos.ColAlignment(1) = 4
End Sub
Private Sub Grilla()
Dim i As Integer
GrillaDatos.Clear
Estructura
GrillaDatos.Rows = rs.RecordCount + 1
i = 1
rs.MoveFirst
Do While rs.EOF = False
i = i + 1
GrillaDatos.TextMatrix(i, 0) = rs!CVE_Titulo
GrillaDatos.TextMatrix(i, 1) = rs!CVE_Mail
rs.MoveNext
i = i + 1
Loop
rs.Close
End Sub
But when i press button, it shows the next error:
runtime error Run time error'-2147217887(80040e21) odbc driver doesnt support requested properties.
In this line:
rs.Open "SELECT CorridaVigenciaEncabezado.CVE_Titulo, CorridaVigenciaEncabezado.CVE_Mail " _
& "FROM CorridaVigenciaEncabezado INNER JOIN Usuarios " _
& "ON CorridaVigenciaEncabezado.USU_IdSolicitado = Usuarios.Codigo " _
& "INNER JOIN Solicitud on CorridaVigenciaEncabezado.CVE_Titulo = Solicitud.ANTITSOL " _
& "WHERE Solicitud.ANDNICLI =19002108 ", Cn, adOpenKeyset, adLockReadOnly
So, can anyone tells me what's wrong with my code? 'cause i don't understand what's wrong. i had readed about this problem and i don't know to do
Just in case the ODBC driver doesn't support the CursorType, try changing the CursorType in the Open method of the Recordset object.
You can try with adOpenStatic or adOpenUnspecified.
..., Cn, adOpenStatic, adLockReadOnly
Updated code. I think its close but the dgv doesn't load with any data.
Public Class CloseJob
Public sqlcon As String = My.Settings.New_Assembly_AccessConnectionString
Public con As New SqlConnection(sqlcon)
Public job As String
Public Async Function GetDataAsync(ByVal sql As String, ByVal sqlcon As String) As Task(Of DataTable)
Dim dt As New DataTable
Dim cmd As New SqlCommand(sql, con)
Using da = New SqlDataAdapter(sql, sqlcon)
da.SelectCommand = cmd
cmd.Parameters.AddWithValue("#Job2", job)
Await Task.Run(Function()
da.Fill(dt)
End Function)
End Using
Return dt
End Function
Public Async Sub Button_Click(sender As Object, e As RoutedEventArgs)
Refresh.Visibility = Windows.Visibility.Visible
txtJob.IsEnabled = False
btnEnter.IsEnabled = False
Try
job = txtJob.Text
Dim sqlcon As String = My.Settings.New_Assembly_AccessConnectionString
Dim sql As String
sql = "SELECT isnull(p.[CLASS],j.class) as 'CLASS',isnull([SERIAL_NUMBER],left(year(d.cup_mfg_date),2) + d.cup_serial) as SERIAL, " & _
"isnull([CUP_DATE],d.cup_mfg_date) as CUPDATE, isnull([CUP_PART_NUM],left([Cup#],charindex('-',Cup#)-1)) as PARTNUM, isnull(p.[LATERAL_VALUE], " & _
"d.lateral_value * 10000) as LATVALUE, isnull([LAT_UPPER],0) as LAT_UPPER,isnull([LAT_LOWER],0) as LAT_LOWER, " & _
"isnull(p.[BEFORE_WEIGHT],0) as BEFORE_WEIGHT, isnull(p.[AFTER_WEIGHT],0) as AFTER_WEIGHT,isnull([GREASE_UPPER],0) as GREASE_UPPER, " & _
"isnull([GREASE_LOWER],0) as GREASE_LOWER,isnull(p.[SPACER_MEASURE], d.Spacer_Measure) as SPACER,isnull([QTY_SPACER_CHANGE],0) as 'CHANGES', " & _
"isnull([LATERAL_DATE_TIME],'1999-11-11 11:11:11.111') as LATERAL_DATE_TIME, " & _
"isnull([GREASE_DATE_TIME],'1999-11-11 11:11:11.111') as GREASE_DATE_TIME, isnull([LINE_NUM],d.linenum) as LINE, " & _
"isnull(BAD_PART, 'BAD_INFO') as Result, isnull([AIR_PRESSURE1], 0) as PRESSURE " & _
"FROM [NB_ASSEMBLY].[dbo].[PieceData] p full outer JOIN New_Assembly_Access.dbo.Tbl_Data AS d " & _
"ON substring(d.zbarcode,3,6) = right(p.serial_number,6) and month(d.cup_mfg_date) = month(p.cup_date) and " & _
"right(d.zbarcode,10) = right(p.cup_part_num,10) join new_assembly_Access.dbo.tbl_job j on j.job# = d.job# where d.job# = #Job2"
con.Open()
Dim data = Await GetDataAsync(sql, sqlcon)
dgvJob.DataContext = data
dgvJob.AutoGenerateColumns = True
dgvJob.CanUserAddRows = False
Catch ex As Exception
End Try
Refresh.Visibility = Windows.Visibility.Hidden
End Sub
Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
Refresh.Visibility = Windows.Visibility.Hidden
txtJob.Focus()
End Sub
End Class
I recommend you clean your code up a bit and make methods that only do one thing - don't have a ReadDatabase that also fiddles with controls etc
DataAdapter can take a sql string and a connection string, it knows how to make a connection and open it etc. It tidies things up to hand all that off to the DA
And maybe put that massive SQL string into a Resources file
Private Async Function GetComponentsDataTable() as Task(Of DataTable)
Dim con As String = My.Settings.New_Assembly_AccessConnectionString
Dim sql as String = "SELECT isnull(p.[CLASS],j.class) as 'CLASS',isnull([SERIAL_NUMBER],left(year(d.cup_mfg_date),2) + d.cup_serial) as SERIAL, " & _
"isnull([CUP_DATE],d.cup_mfg_date) as CUPDATE, isnull([CUP_PART_NUM],left([Cup#],charindex('-',Cup#)-1)) as PARTNUM, isnull(p.[LATERAL_VALUE], " & _
"d.lateral_value * 10000) as LATVALUE, isnull([LAT_UPPER],0) as LAT_UPPER,isnull([LAT_LOWER],0) as LAT_LOWER, " & _
"isnull(p.[BEFORE_WEIGHT],0) as BEFORE_WEIGHT, isnull(p.[AFTER_WEIGHT],0) as AFTER_WEIGHT,isnull([GREASE_UPPER],0) as GREASE_UPPER, " & _
"isnull([GREASE_LOWER],0) as GREASE_LOWER,isnull(p.[SPACER_MEASURE], d.Spacer_Measure) as SPACER,isnull([QTY_SPACER_CHANGE],0) as 'CHANGES', " & _
"isnull([LATERAL_DATE_TIME],'1999-11-11 11:11:11.111') as LATERAL_DATE_TIME, " & _
"isnull([GREASE_DATE_TIME],'1999-11-11 11:11:11.111') as GREASE_DATE_TIME, isnull([LINE_NUM],d.linenum) as LINE, " & _
"isnull(BAD_PART, 'BAD_INFO') as Result, isnull([AIR_PRESSURE1], 0) as PRESSURE " & _
"FROM [NB_ASSEMBLY].[dbo].[PieceData] p full outer JOIN New_Assembly_Access.dbo.Tbl_Data AS d " & _
"ON substring(d.zbarcode,3,6) = right(p.serial_number,6) and month(d.cup_mfg_date) = month(p.cup_date) and " & _
"right(d.zbarcode,10) = right(p.cup_part_num,10) join new_assembly_Access.dbo.tbl_job j on j.job# = d.job# where d.job# = #Job2"
Using da as New SqlDataAdapter(sql, con)
da.SelectCommand.Parameters.AddWithValue("#Job2", job) 'see https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/'
Dim dt As New DataTable
Await Task.Run(Sub() da.Fill(dt)) 'also, see note from AlexB
Return dt
End Using
End Sub
Public Async Sub Button_Click(sender As Object, e As RoutedEventArgs)
txtJob.IsEnabled = False
btnEnter.IsEnabled = False
Dim dt = Await GetComponentsDataTable()
dgvJob.AutoGenerateColumns = True
dgvJob.DataContext = dt.DefaultView
dgvJob.CanUserAddRows = False
End Sub
Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
txtJob.Focus()
End Sub
This is your code modified on the fly, start from here as I don’t know if works well or if there needs changes without your database and other parameters.
Public con As New SqlConnection
Public job As String
Private Sub ReadDatabase()
Dim bgThread As Threading.Thread = New Threading.Thread(Sub()
Dim sqlcon As String = My.Settings.New_Assembly_AccessConnectionString
Dim sql As New SqlCommand
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Using con = New SqlConnection(sqlcon)
con.Open()
sql = New SqlCommand("SELECT isnull(p.[CLASS],j.class) as 'CLASS',isnull([SERIAL_NUMBER],left(year(d.cup_mfg_date),2) + d.cup_serial) as SERIAL, " &
"isnull([CUP_DATE],d.cup_mfg_date) as CUPDATE, isnull([CUP_PART_NUM],left([Cup#],charindex('-',Cup#)-1)) as PARTNUM, isnull(p.[LATERAL_VALUE], " &
"d.lateral_value * 10000) as LATVALUE, isnull([LAT_UPPER],0) as LAT_UPPER,isnull([LAT_LOWER],0) as LAT_LOWER, " &
"isnull(p.[BEFORE_WEIGHT],0) as BEFORE_WEIGHT, isnull(p.[AFTER_WEIGHT],0) as AFTER_WEIGHT,isnull([GREASE_UPPER],0) as GREASE_UPPER, " &
"isnull([GREASE_LOWER],0) as GREASE_LOWER,isnull(p.[SPACER_MEASURE], d.Spacer_Measure) as SPACER,isnull([QTY_SPACER_CHANGE],0) as 'CHANGES', " &
"isnull([LATERAL_DATE_TIME],'1999-11-11 11:11:11.111') as LATERAL_DATE_TIME, " &
"isnull([GREASE_DATE_TIME],'1999-11-11 11:11:11.111') as GREASE_DATE_TIME, isnull([LINE_NUM],d.linenum) as LINE, " &
"isnull(BAD_PART, 'BAD_INFO') as Result, isnull([AIR_PRESSURE1], 0) as PRESSURE " &
"FROM [NB_ASSEMBLY].[dbo].[PieceData] p full outer JOIN New_Assembly_Access.dbo.Tbl_Data AS d " &
"ON substring(d.zbarcode,3,6) = right(p.serial_number,6) and month(d.cup_mfg_date) = month(p.cup_date) and " &
"right(d.zbarcode,10) = right(p.cup_part_num,10) join new_assembly_Access.dbo.tbl_job j on j.job# = d.job# where d.job# = #Job2", con)
sql.Parameters.AddWithValue("#Job2", job)
da.SelectCommand = sql
Dim dt As New DataTable
da.Fill(dt)
Invoke(Sub()
dgvJob.DataContext = dt.DefaultView
dgvJob.AutoGenerateColumns = True
dgvJob.CanUserAddRows = False
End Sub)
End Using
End Sub) With {
.IsBackground = True
}
bgThread.Start()
End Sub
Public Sub Button_Click(sender As Object, e As RoutedEventArgs)
txtJob.IsEnabled = False
btnEnter.IsEnabled = False
job = txtJob.Text
ReadDatabase()
End Sub
Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
txtJob.Focus()
End Sub
I have two listviews, lvNum having one column and lvList have 8 columns. I want to populate my lvList from my access database through my lvNum . If I click a row in my lvNum, my lvList items will be added from the database. If I click once the lvList is populated,but when I click another cell it gives me an error
InvalidArgument=Value of '0' is not valid for 'index'.
This is my code to load the record to all my listviews
Public Sub loadRecord(lv As ListView, sql As String, noOfIndex As Integer)
Try
lv.Items.Clear()
Dim lvcmd As OleDbCommand = New OleDbCommand(sql, konek)
Dim lvdr As OleDbDataReader = lvcmd.ExecuteReader
If lvdr.HasRows Then
While lvdr.Read
Dim newLv As New ListViewItem
newLv.Text = lvdr.GetValue(0)
For item As Integer = 1 To noOfIndex
newLv.SubItems.Add(lvdr.GetValue(item))
Next
lv.Items.Add(newLv)
End While
End If
Catch ex As Exception
MsgBox(ex.Message, , "Load Record Error")
End Try
End Sub
I call the sub in the lvNum selectedIndexChanged event
Private Sub lvNum_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lvNum.SelectedIndexChanged
'this is where I get my error
Dim joindRecord As String = "SELECT tblProducts.prodName,tblProducts.prodCode,tblProducts.Description," & _
"tblProducts.prodCost,tblPurchaseOrder.POQty,tblPurchaseOrder.PODiscount, tblPurchaseOrder.total," & _
"tblPurchaseOrder.prodID,tblProducts.prodID,tblPurchaseOrder.PONumber " & _
"FROM tblProducts INNER JOIN tblPurchaseOrder ON tblProducts.prodID = tblPurchaseOrder.prodID " & _
"WHERE tblPurchaseOrder.PONumber ='" & lvNum.SelectedItems.Item(0).Text & "'"
Call loadRecord(lvList, joindRecord, 7)
End Sub
I figured it out I added this piece of code
If lvPO.SelectedItems.Count <> 0 Then
'code goes here
End If
So the code goes like this
Private Sub lvNum_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lvNum.SelectedIndexChanged
If lvPO.SelectedItems.Count <> 0 Then
Dim joindRecord As String = "SELECT tblProducts.prodName,tblProducts.prodCode,tblProducts.Description," & _
"tblProducts.prodCost,tblPurchaseOrder.POQty,tblPurchaseOrder.PODiscount, tblPurchaseOrder.total," & _
"tblPurchaseOrder.prodID,tblProducts.prodID,tblPurchaseOrder.PONumber " & _
"FROM tblProducts INNER JOIN tblPurchaseOrder ON tblProducts.prodID = tblPurchaseOrder.prodID " & _
"WHERE tblPurchaseOrder.PONumber ='" & lvNum.SelectedItems.Item(0).Text & "'"
Call loadRecord(lvList, joindRecord, 7)
End If
End Sub
I'm really sorry to be asking and I'm sure it's extremely simple to answer but whenever I try to run the macro in excel below, I get the error message stated in the title:
Sub CallsMacro()
Dim ConData As ADODB.Connection
Dim rstData As ADODB.Recordset
Dim wsSheet As Worksheet
Dim strServer As String
Dim strDatabase As String
Dim strFrom As String
Dim strto As String
Dim intCount As Integer
Set wsSheet = ActiveWorkbook.Worksheets("Refresh")
With wsSheet
strServer = "TNS-CCR-02"
strDatabase = "AvayaSBCCRT"
strFrom = .Range("C$2")
strto = .Range("C$3")
End With
Set ConData = New ADODB.Connection
With ConData
.ConnectionString = "Provider=SQLOLEDB;Data Source=" & strServer & ";" & "Initial Catalog=" & ";" & "persist security info=true;" & "User Id=dashboard; Password=D4$hboard;"
.CommandTimeout = 1800
.Open
End With
''Create the recordset from the SQL query
Set rstData = New ADODB.Recordset
Set wsSheet = ActiveWorkbook.Worksheets("Calls")
With rstData
.ActiveConnection = ConData
.Source = "SELECT DISTINCT CAST(c.createdate AS date) as [Date]," & _
"CASE WHEN c.[CategoryID] = 1 then 'Outbound' WHEN c.[CategoryID] = 2 then 'Inbound' Else 'Internal' end as [Direction], c.cli as [Number], c.ddi, 'CallCentre' as [Queue], '' as [Queue Time], u.username as [Agent], cast((c.DestroyDate - c.CreateDate) as TIME) as [Duration], 'Connected' as [Status], c.callID as [Reference]" & _
"FROM [AvayaSBCCRT].[dbo].[tblAgentActivity] as a" & _
"JOIN [AvayaSBCCRT].[dbo].[tblCallList] as c on c.calllistid = a.calllistid" & _
"JOIN [AvayaSBCCRT].[dbo].[tblUsers] as u on u.userid = a.AgentID" & _
"WHERE c.createdate between '" & strFrom & "' and '" & strto & "'" & _
"AND a.[ActivityID] = 3 "
.CursorType = adOpenForwardOnly
.Open
End With
wsSheet.Activate
Dim Lastrow As Long
Lastrow = Range("A" & Rows.Count).end(xlUp).Row
Range("A2:J" & Lastrow).ClearContents
If rs.EOF = False Then wsSheet.Cells(2, 1).CopyFromRecordset rsData
rs.Close
Set rs = Nothing
Set cmd = Nothing
con.Close
Set con = Nothing
End Sub
I've looked high and low and cannot find the reason for it. Anybody have any ideas?
You're missing spaces from the end of the lines. Your SQL contains for example:
[tblAgentActivity] as aJOIN [AvayaSBCCRT].[dbo].[tblCallList]