Object reference not set to an instance of an object - vb.net

Can anyone help with the following code?
I'm trying to get data from the database colum to the datagridview...
I'm getting error over here "Dim sql_1 As String = "SELECT * FROM item where item_id = '" + DataGridView_stockout.CurrentCell.Value.ToString() + "'""
Private Sub DataGridView_stockout_CellMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView_stockout.CellMouseClick
Dim i As Integer = Stock_checkDataSet1.Tables(0).Rows.Count > 0
Dim thiscur_stok As New System.Data.SqlClient.SqlConnection("Data Source=MBTHQ\SQLEXPRESS;Initial Catalog=stock_check;Integrated Security=True")
' Sql Query
Dim sql_1 As String = "SELECT * FROM item where item_id = '" + DataGridView_stockout.CurrentCell.Value.ToString() + "'"
' Create Data Adapter
Dim da_1 As New SqlDataAdapter(sql_1, thiscur_stok)
' Fill Dataset and Get Data Table
da_1.Fill(Stock_checkDataSet1, "item")
Dim dt_1 As DataTable = Stock_checkDataSet1.Tables("item")
If i >= DataGridView_stockout.Rows.Count Then
'MessageBox.Show("Sorry, DataGridView_stockout doesn't any row at index " & i.ToString())
Exit Sub
End If
If 1 >= Stock_checkDataSet1.Tables.Count Then
'MessageBox.Show("Sorry, Stock_checkDataSet1 doesn't any table at index 1")
Exit Sub
End If
If i >= Stock_checkDataSet1.Tables(1).Rows.Count Then
'MessageBox.Show("Sorry, Stock_checkDataSet1.Tables(1) doesn't any row at index " & i.ToString())
Exit Sub
End If
If Not Stock_checkDataSet1.Tables(1).Columns.Contains("os") Then
'MessageBox.Show("Sorry, Stock_checkDataSet1.Tables(1) doesn't any column named 'os'")
Exit Sub
End If
'DataGridView_stockout.Item("cs_stockout", i).Value = Stock_checkDataSet1.Tables(0).Rows(i).Item("os")
Dim ab As String = Stock_checkDataSet1.Tables(0).Rows(i)(0).ToString()
End Sub
I keep on getting the error saying "Object reference not set to an instance of an object"
I dont know where I'm going wrong.
Help really appreciated!!

Stock_checkDataSet1.Tables(1)
I think you need to use a 0 index.

Start the debugger and turn on break on exception, you'll see the exact point where the exception occurs then.

Related

Data Type Mismatch on SQL statement

I am trying to pull in column data from a table into a timer in VBA. In my table I have IntervalSeconds as a number. I'm trying to query the number of seconds to determine how long to set my counter for.
Dim timeRemaining As Long (Form Variable) - used in multiple functionss
Private Sub Form_Open(Cancel As Integer)
Dim strSQL As String
Me.Visible = False
strSQL = "SELECT AccessControl.IntervalSeconds FROM AccessControl WHERE AccessControl.DatabaseName = '" & CurrentDb.Name & "'"
timeRemaining = CLng(strSQL)
DoCmd.OpenForm ("frmForceLogout")
End Sub
Every time I run the form I get a Type Mismatch error when I hit the timeRemaining = cLng(strSQL) line. Am I missing something?
You can use DLookup for such simple tasks:
Private Sub Form_Open(Cancel As Integer)
Dim Criteria As String
Me.Visible = False
Criteria = "DatabaseName = '" & CurrentDb.Name & "'"
timeRemaining = DLookup("IntervalSeconds", "AccessControl", Criteria)
DoCmd.OpenForm ("frmForceLogout")
End Sub

Retrieving MS Access Database to vb6 and filter data using 2 DTpicker for the sum rate

Private Sub Command5_Click()
Dim li As ListItem
Dim lngRunningTotal As Long
For Each li In ListView1.ListItems
lngRunningTotal = lngRunningTotal + CLng(li.SubItems(6)) 'calculate all the in Total min column
Next
sumText.Text = CStr(lngRunningTotal) 'display total
End Sub
I want to filter data using 2 DTpicker for the sum rate.
Here's how you can do it with the code you posted:
Private Sub Command5_Click()
Dim li As ListItem
Dim lngRunningTotal As Long
Dim iLogDateIndex As Integer
Dim iMinutesIndex As Integer
iLogDateIndex = 5
iMinutesIndex = 6
For Each li In ListView1.ListItems
If CDate(li.SubItems(iLogDateIndex)) >= DTPickerStart And CDate(li.SubItems(iLogDateIndex)) <= DTPickerEnd Then
lngRunningTotal = lngRunningTotal + CInt(li.SubItems(iMinutesIndex)) ' calculate all the in Total min column
End If
Next
' Display total
sumText.Text = CStr(lngRunningTotal)
End Sub
The following demonstrates how to filter your data using an SQL Statement:
Private Sub cmdQuery_Click()
Dim objAdoConnection As New ADODB.Connection
Dim objRecordset As ADODB.Recordset
Dim sConnectionString As String
Dim sSQLStatement As String
Dim sDatabaseFile As String
Dim itm As ListItem
' Path to Access database
sDatabaseFile = "C:\Temp\Stack\ADO\Database.accdb"
' Connection string
sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & sDatabaseFile
' Open Connection
objAdoConnection.Open sConnectionString
' Open recordset with SQL query
sSQLStatement = "SELECT * FROM TimeCards WHERE WorkDate BETWEEN #" & DTPickerStart & "# AND #" & DTPickerEnd & "#"
Set objRecordset = objAdoConnection.Execute(sSQLStatement)
' Clear ListView
ListView1.ListItems.Clear
' Move Recordset to first record
objRecordset.MoveFirst
' Display record data
Do While Not objRecordset.EOF
' Add record to ListView
Set itm = ListView1.ListItems.Add(, , objRecordset.Fields("ID"))
itm.SubItems(1) = objRecordset.Fields("EmployeeID")
itm.SubItems(2) = objRecordset.Fields("WorkDate")
itm.SubItems(3) = objRecordset.Fields("WorkHours")
' Move to next record
objRecordset.MoveNext
Loop
' Close connection and release objects
objAdoConnection.Close
Set objRecordset = Nothing
Set objAdoConnection = Nothing
End Sub
I made a quick UI with two DTPicker controls and a Query button. The results get shown into a ListView control:
I also created a simple TimeCards table with the following data for testing:
You can research SQL Statements on the internet and find many ways you can filter your data.

VB How to Clear existing items in listview

I am trying to search the information from the sql server then show at the listview. Everytime I click search it won't clear the existing records based on the past time searching. I've tried item.clear, it will only show me the new search but it won't clear all the existing records. Can someone help please?
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim strNameSource As String
Dim strPhoneSource As String
Dim strBothSource As String
If OpenConnect() = True Then
Try
If ChkCustName.Checked = True Then
strNameSource = "SELECT TCI.strLastName + ', ' + TCI.strFirstName AS strName,TCI.strPhoneNumber,CONVERT(VARCHAR,TCI.dtmCheckIn, 101),CONVERT(VARCHAR,TCI.dtmCheckOut,101),TRT.strRoomType,TR.strRoom FROM TCheckInInfo AS TCI,TRoom AS TR,TRoomType AS TRT WHERE TCI.intRoomID = TR.intRoomID AND TR.intRoomTypeID = TRT.intRoomTypeID AND intCheckInStatusID = 1 AND TCI.strLastName ='" & txtLastName.Text & "'"
SearchReservation(strNameSource)
ElseIf ChkPhoneNumber.Checked = True Then
strPhoneSource = "SELECT TCI.strLastName + ', ' + TCI.strFirstName AS strName,TCI.strPhoneNumber,CONVERT(VARCHAR,TCI.dtmCheckIn, 101),CONVERT(VARCHAR,TCI.dtmCheckOut,101),TRT.strRoomType,TR.strRoom FROM TCheckInInfo AS TCI,TRoom AS TR,TRoomType AS TRT WHERE TCI.intRoomID = TR.intRoomID AND TR.intRoomTypeID = TRT.intRoomTypeID AND intCheckInStatusID = 1 AND TCI.strPhoneNumber ='" & txtPhoneNumber.Text & "'"
SearchReservation(strPhoneSource)
ElseIf ChkCustName.Checked = True And ChkPhoneNumber.Checked = True Then
strBothSource = "SELECT TCI.strLastName + ', ' + TCI.strFirstName AS strName,TCI.strPhoneNumber,CONVERT(VARCHAR,TCI.dtmCheckIn, 101),CONVERT(VARCHAR,TCI.dtmCheckOut,101),TRT.strRoomType,TR.strRoom FROM TCheckInInfo AS TCI,TRoom AS TR,TRoomType AS TRT WHERE TCI.intRoomID = TR.intRoomID AND TR.intRoomTypeID = TRT.intRoomTypeID AND intCheckInStatusID = 1 AND TCI.strPhoneNumber ='" & txtPhoneNumber.Text & "' AND TCI.strLastName ='" & txtLastName.Text & "'"
SearchReservation(strBothSource)
End If
txtLastName.Clear()
txtPhoneNumber.Clear()
Catch excError As Exception
WriteLog(excError)
'End program
Application.Exit()
End Try
End If
End Sub
Private Sub SearchReservation(ByVal strSource As String)
Dim itemcollection(100) As String
Dim Row As Integer
Dim Column As Integer
Dim ListViewItem As New ListViewItem
lstReservation.Items.Clear()
Try
cmd = New OleDb.OleDbCommand(strSource, cnn)
Adapter = New OleDb.OleDbDataAdapter(cmd)
Adapter.Fill(Ds, "Table")
'Now adding the Items in Listview
If Ds.Tables(0).Rows.Count = 0 Then
' Something went wrong. warn user
MessageBox.Show(Me, "Could not find the Customer", "Customer finding Error", _
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
lstReservation.BeginUpdate()
For Row = 0 To Ds.Tables(0).Rows.Count - 1
For Column = 0 To Ds.Tables(0).Columns.Count - 1
itemcollection(Column) = Ds.Tables(0).Rows(Row)(Column).ToString()
Next
ListViewItem = New ListViewItem(itemcollection)
lstReservation.Items.Add(ListViewItem)
Next
lstReservation.EndUpdate()
End If
Catch excError As Exception
WriteLog(excError)
'End program
Application.Exit()
End Try
End Sub
Lots of issues with your code, but I'll focus on your immediate issue.
You keep filling the DataSet with new tables, but you keep using the original table that is still in position zero of the DataSet.
I would venture a guess that you need to clear the rows of your DataTable:
If Ds.Tables.Contains("Table") Then
Ds.Tables("Table").Rows.Clear()
End If
lstReservation.Items.Clear()
of just clear any tables there:
Ds.Tables.Clear()
lstReservation.Items.Clear()

VB.Net Global DataSets inside a public function

I am having some problem with a function that I hope you can help.
My Application is a simple one, it uses an Access database to load employee information and creates letters and financial breakdown sheet from word templates that users can then print and save back to the database.
I started by creating a dataset containing several datatables for each form subroutine but it resulted in literally hundreds of lines of repeated code. But it worked.
What I want to do, is have one dataset containing all the information needed about an employee and be able to reference it over several forms at the same time. So i created a public module that looks like this:
Public Module Datasets
Public update As String
Dim pCn As OleDb.OleDbConnection
Public Function CSofwareDataSet() As DataSet
'open new connection to database
pCn = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\CGI Project\CorrespondenceSoftware\Database1.accdb; Persist Security Info=False;")
Try
Call pCn.Open() 'opens the connection
Catch ex As Exception
MessageBox.Show("Could not open a database connection! 1")
MessageBox.Show(ex.ToString)
End Try
CSofwareDataSet = New DataSet
Dim daOPG As New OleDb.OleDbDataAdapter("SELECT * FROM Overpayment WHERE PayNumber='" & Main.tbPayNumber.Text & "' AND Gross=1", pCn) 'get all data from Overpayment Details table
Dim daOPN As New OleDb.OleDbDataAdapter("SELECT * FROM Overpayment WHERE PayNumber='" & Main.tbPayNumber.Text & "' AND Net=1", pCn) 'get all data from Overpayment Details table
Dim daOPR As New OleDb.OleDbDataAdapter("SELECT * FROM OvpReasons", pCn) 'get overpayment reasons
Dim daREC As New OleDb.OleDbDataAdapter("SELECT * FROM TaxYear", pCn) 'get recovery date options
Dim daEMP As New OleDb.OleDbDataAdapter("SELECT * FROM EmployeeDetails WHERE PayNumber='" & Main.tbPayNumber.Text & "' AND Active=1 ", pCn) 'get all data from Employee Details table
Dim daCON As New OleDb.OleDbDataAdapter("SELECT * FROM Consultant", pCn) 'get all data from Consultant Details table
Dim daSET As New OleDb.OleDbDataAdapter("SELECT * FROM Settings", pCn) 'get all data from Consultant Details table
'Find the primary key (if missing)
daOPG.MissingSchemaAction = MissingSchemaAction.AddWithKey
daOPN.MissingSchemaAction = MissingSchemaAction.AddWithKey
daOPR.MissingSchemaAction = MissingSchemaAction.AddWithKey
daREC.MissingSchemaAction = MissingSchemaAction.AddWithKey
daEMP.MissingSchemaAction = MissingSchemaAction.AddWithKey
daCON.MissingSchemaAction = MissingSchemaAction.AddWithKey
daSET.MissingSchemaAction = MissingSchemaAction.AddWithKey
'setup prefixes
Dim cbOPG As New OleDb.OleDbCommandBuilder(daOPG)
cbOPG.QuotePrefix = "["
cbOPG.QuoteSuffix = "]"
Dim cbOPN As New OleDb.OleDbCommandBuilder(daOPN)
cbOPG.QuotePrefix = "["
cbOPG.QuoteSuffix = "]"
Dim cbOPR As New OleDb.OleDbCommandBuilder(daOPR)
cbOPG.QuotePrefix = "["
cbOPG.QuoteSuffix = "]"
Dim cbREC As New OleDb.OleDbCommandBuilder(daREC)
cbOPG.QuotePrefix = "["
cbOPG.QuoteSuffix = "]"
Dim cbEMP As New OleDb.OleDbCommandBuilder(daEMP)
cbEMP.QuotePrefix = "["
cbEMP.QuoteSuffix = "]"
Dim cbCON As New OleDb.OleDbCommandBuilder(daCON)
cbEMP.QuotePrefix = "["
cbEMP.QuoteSuffix = "]"
Dim cbSET As New OleDb.OleDbCommandBuilder(daSET)
cbEMP.QuotePrefix = "["
cbEMP.QuoteSuffix = "]"
If CSofwareDataSet.HasChanges Then
Try
daEMP.Update(CSofwareDataSet, "EmployeeDetails")
daOPG.Update(CSofwareDataSet, "OverPaymentGross")
daOPN.Update(CSofwareDataSet, "OverPaymentNet")
daSET.Update(CSofwareDataSet, "Settings")
MessageBox.Show("Success! Records updated.")
update = "0"
Catch ex As Exception
MessageBox.Show("Oops - something went wrong and it didn't update")
update = "0"
End Try
ElseIf CSofwareDataSet.Tables.Count = 0 Then
daOPG.Fill(CSofwareDataSet, "OverPaymentGross")
daOPN.Fill(CSofwareDataSet, "OverPaymentNet")
daOPR.Fill(CSofwareDataSet, "OverPaymentReasons")
daREC.Fill(CSofwareDataSet, "RecoveryDates")
daEMP.Fill(CSofwareDataSet, "EmployeeDetails")
daCON.Fill(CSofwareDataSet, "ConsultantDetails")
daSET.Fill(CSofwareDataSet, "Settings")
End If
'If update = "1" Then
' Try
' daEMP.Update(CSofwareDataSet, "EmployeeDetails")
' daOPG.Update(CSofwareDataSet, "OverPaymentGross")
' daOPN.Update(CSofwareDataSet, "OverPaymentNet")
' daSET.Update(CSofwareDataSet, "Settings")
'
' MessageBox.Show("Success! Records updated.")
' update = "0"
' Catch ex As Exception
' MessageBox.Show("Oops - something went wrong and it didn't update")
' update = "0"
' End Try
' End If
pCn.Close()
End Function
End Module
On each form, it gets referenced like this (as an example):
Imports WeifenLuo.WinFormsUI.Docking
Imports Word = Microsoft.Office.Interop.Word
Imports CorrespondenceSoftware.Datasets
Public Class GrossInput
Dim loading = "1"
Dim NewEmployee = "0" 'sets the default new employee flag to 0
Private pCn As OleDb.OleDbConnection
Private Sub GrossInput_Load(ByVal Sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Try
If CSofwareDataSet.Tables("EmployeeDetails").Rows.Count > 0 Then
For i As Integer = 0 To CSofwareDataSet.Tables("EmployeeDetails").Rows.Count - 1
cbTitle.Text = CSofwareDataSet.Tables("EmployeeDetails").Rows(i)(2)
tbFName.Text = CSofwareDataSet.Tables("EmployeeDetails").Rows(i)(3)
tbLName.Text = CSofwareDataSet.Tables("EmployeeDetails").Rows(i)(4)
tbAddress1.Text = CSofwareDataSet.Tables("EmployeeDetails").Rows(i)(5)
tbAddress2.Text = CSofwareDataSet.Tables("EmployeeDetails").Rows(i)(6)
tbAddress3.Text = CSofwareDataSet.Tables("EmployeeDetails").Rows(i)(7)
tbAddress4.Text = CSofwareDataSet.Tables("EmployeeDetails").Rows(i)(8)
tbPostcode.Text = CSofwareDataSet.Tables("EmployeeDetails").Rows(i)(9)
tbWorkLocation.Text = CSofwareDataSet.Tables("EmployeeDetails").Rows(i)(10)
tbWorkLocation.Enabled = False
tbPostcode.Enabled = False
tbAddress4.Enabled = False
tbAddress3.Enabled = False
tbAddress2.Enabled = False
tbAddress1.Enabled = False
tbLName.Enabled = False
tbFName.Enabled = False
cbTitle.Enabled = False
chkMSC.Enabled = False
chkOfficer.Enabled = False
chkStaff.Enabled = False
bnSaveEmp.Enabled = False
bnEditEmp.Enabled = True
Next
End If
If CSofwareDataSet.Tables("EmployeeDetails").Rows(0)(11) = "1" Then
chkOfficer.Checked = True
Else
chkOfficer.Checked = False
End If
If CSofwareDataSet.Tables("EmployeeDetails").Rows(0)(12) = "1" Then
chkStaff.Checked = True
Else
chkStaff.Checked = False
End If
If CSofwareDataSet.Tables("EmployeeDetails").Rows(0)(13) = "1" Then
chkMSC.Checked = True
Else
chkMSC.Checked = False
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
MessageBox.Show("Employee not found. Ensure pay number is correct and create a new record")
NewEmployee = "1" ' tells the program to create a new record if saved
cbReference.Enabled = False
cbReference.Text = ""
bnEditEmp.Enabled = False
End Try
'display the overpayment references to the user
If CSofwareDataSet.Tables("OverPaymentGross").Rows.Count > 0 Then
For i As Integer = 0 To CSofwareDataSet.Tables("OverPaymentGross").Rows.Count - 1
cbReference.Items.Add(CSofwareDataSet.Tables("OverPaymentGross").Rows(i)(2))
Next
End If
'display the available consultants to the user
If CSofwareDataSet.Tables("ConsultantDetails").Rows.Count > 0 Then
For i As Integer = 0 To CSofwareDataSet.Tables("ConsultantDetails").Rows.Count - 1
cbConsultant.Items.Add(CSofwareDataSet.Tables("ConsultantDetails").Rows(i)(1) & " " & CSofwareDataSet.Tables("ConsultantDetails").Rows(i)(2))
Next
End If
'display the available Overpayment reasons to the user
If CSofwareDataSet.Tables("OverPaymentReasons").Rows.Count > 0 Then
For i As Integer = 0 To CSofwareDataSet.Tables("OverPaymentReasons").Rows.Count - 1
cbReason.Items.Add(CSofwareDataSet.Tables("OverPaymentReasons").Rows(i)(1))
Next
End If
'Load other recovery date options
If CSofwareDataSet.Tables("RecoveryDates").Rows.Count > 0 Then
For i As Integer = 0 To CSofwareDataSet.Tables("RecoveryDates").Rows.Count - 1
cbStartRecovery.Items.Add(CSofwareDataSet.Tables("RecoveryDates").Rows(i)(1))
Next
End If
Catch ex As Exception
MessageBox.Show(ex.ToString) 'Show any errors to the user
End Try
loading = "0"
End Sub
Now! the problem that I'm having is that, this does work and run without any errors BUT every time the CSSoftwareDataSet function runs it populates the tables correctly and returns the expected results but it then deletes the datatable data so every time the function is referenced from a winform it needs to haul all the data from the access database from scratch, severely impacting on the performance of the program. The tables wont update properly because its not storing the datatable information and as soon as its inserted its forgotten but again, produces no errors. An example of my update script looks like this:
Else 'create a new record
'create a new reference
Dim REFRowCount = CSofwareDataSet.Tables("OverPaymentGross").Rows.Count + 1 'count the number of rows in table and add 1
Dim NewREF = "OVPG" & Main.tbPayNumber.Text & "-" & REFRowCount
'Find todays date and reply dates
Dim TodayDatedate = Format(Now.Date(), "dd/MM/yyyy")
Dim ReplyDatedate = Format(Now.Date.AddDays(21), "dd/MM/yyyy")
'Create a new row
Dim OPNew As DataRow = CSofwareDataSet.Tables("OverPaymentGross").NewRow() 'create a variable to contain the new row
OPNew.Item(1) = Main.tbPayNumber.Text
OPNew.Item(2) = NewREF
OPNew.Item(3) = tbOverpaymentAmount.Text.ToString
OPNew.Item(4) = tbMonRec.Text
OPNew.Item(5) = tbTaxP.Text
OPNew.Item(6) = TodayDatedate
OPNew.Item(7) = ReplyDatedate
OPNew.Item(8) = tbMoRep.Text
OPNew.Item(9) = cbStartRecovery.Text
OPNew.Item(10) = "1" 'Set as gross
OPNew.Item(11) = "0" 'do not set as net
OPNew.Item(12) = cbReason.Text
OPNew.Item(13) = tbAI.Text
OPNew.Item(14) = dtpStart.Value.Date
OPNew.Item(15) = dtpFinish.Value.Date
OPNew.Item(16) = cbConsultant.Text
OPNew.Item(17) = tbPosition.Text
Call CSofwareDataSet.Tables("OverPaymentGross").Rows.Add(OPNew) 'fill the new row and insert the data
There must be a solution to this. To create a dataset that holds its data in session while you open other winforms until it is reset. I'm out of ideas because i really don't want to go back to repeating all this code for practically every subroutine in my program.
I hope I've explained it OK .. Any help here will be greatly appreciated.
Many thanks,
Shane
You can declare the DataSet globally, populate it in a function (sub), which is called just at the start, and retrieve the information by accessing the variable rather than by calling the function over and over. Your code uses a somehow ambiguous approach (same name for function and for variable) which, together with the VB rules (functions might not include a Return statement but a variable with the function's name) does not play to your favor.
Sample code converting the DataSet into a public variable and renaming the function (and converting it into a sub: what is the point of a function now?):
Public CSofwareDataSet As DataSet
Public Sub populateDS()
'open new connection to database
pCn = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\CGI Project\CorrespondenceSoftware\Database1.accdb; Persist Security Info=False;")
Try
Call pCn.Open() 'opens the connection
Catch ex As Exception
MessageBox.Show("Could not open a database connection! 1")
MessageBox.Show(ex.ToString)
End Try
CSofwareDataSet = New DataSet
'Remaining code
End Sub
Call this sub just once (right at the start of your application; or every time new data has to be retrieved from the DB) and continue using CSofwareDataSet as so far (although as a variable, by removing the Call bits; which, on the other hand, are not required in VB.NET at all).

How can I bind an entity Data Source to the results of a query

I have a query that will go away an and find data
Dim HSNs As String = String.Join(",", ListOfHSNs.Cast(Of String)().ToArray())
Dim query As String = "SELECT VALUE O FROM v_BillData AS O WHERE O.HSNumber IN {'" & HSNs & "'}"
Dim hs As New ObjectQuery(Of v_BillData)(query, CType(Session("ObjectCon"), ObjectContext))
what I now wish to do is to use the results of this query to databind to a EntityDataSource
How can I do this?
You can try to use the Selecting EntityDataSource event like in the following example:
Protected Sub EntityDataSource1_Selecting(ByVal sender As Object, ByVal e As EntityDataSourceSelectingEventArgs)
Dim HSNs As String = String.Join(",", ListOfHSNs.Cast(Of String)().ToArray())
Dim query As String = "SELECT VALUE O FROM v_BillData AS O WHERE O.HSNumber IN {'" & HSNs & "'}"
Dim source As EntityDataSource = Nothing
source = TryCast(Me.Page.FindControl("EntityDataSource1"),EntityDataSource)
If (Not source Is Nothing) Then
source.EntitySetName = Nothing
source.CommandText = query
End If
End Sub
You should set EntitySetName to Nothing because it will throw an error if you have setup EntityDataSource before.