Displaying Data from SQL to vb.net listbox - vb.net

I'm trying to display all the golfer's information from TGolfers into a ListBox. But when I run my code it only displays one golfer's information.
Public Class frmGolfers
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
Dim strSelect As String = ""
Dim strName As String = ""
Dim cmdSelect As OleDb.OleDbCommand ' this will be used for our Select statement
Dim drSourceTable As OleDb.OleDbDataReader ' this will be where our data is retrieved to
Dim dt As DataTable = New DataTable ' this is the table we will load from our reader
' open the database
If OpenDatabaseConnectionSQLServer() = False Then
' No, warn the user ...
MessageBox.Show(Me, "Database connection error." & vbNewLine & _
"The application will now close.",
Me.Text + " Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
' and close the form/application
Me.Close()
End If
' Build the select statement using PK from name selected
strSelect = "SELECT * FROM TGolfers "
' Retrieve all the records
cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
drSourceTable = cmdSelect.ExecuteReader
' load the data table from the reader
dt.Load(drSourceTable)
' populate the text boxes with the data
lbxDisplay.Items.Add(dt.Rows(0).Item(1).ToString & "," & " " & dt.Rows(0).Item(2).ToString &
ControlChars.CrLf & " " & dt.Rows(0).Item(3).ToString & " " & dt.Rows(0).Item(4).ToString & " " & dt.Rows(0).Item(5).ToString & " " & dt.Rows(0).Item(6).ToString)
' close the database connection
CloseDatabaseConnection()
End Sub
End Class

After loading the DataTable start a loop
......
' load the data table from the reader
dt.Load(drSourceTable)
' populate the text boxes with the data
For Each row in dt.Rows
Dim text = row(1).ToString & ", " & _
row(2).ToString & ControlChars.CrLf & " " & _
row(3).ToString & " " & _
row(4).ToString & " " & _
row(5).ToString & " " & _
row(6).ToString
lbxDisplay.Items.Add(text)
Next
......
In this way you loop over each row present in the dt.Rows collection, extract the information needed, build a string and add the string to the ListBox Items collection.
Notice that I have followed your indexing starting from Index = 1 for each column in the DataRow but keep in mind that in NET the array indexing start at index 0 not 1, so the first column of your datarow is at index 0. Change the index in code accordingly to your need. (This means that if you have 6 columns in that table then the indexing should go from 0 to 5, using the index 6 in this scenario gives an Index out of Range exception)

Related

Use SQL code in vba access

I use the following code in vba access to update a column of a table, but it is not working. Please help me.
Best regards.
Dim sqlupdate As String
sqlupdate = "UPDATE Assay" _
& "SET Assay.assay_repeat = " & 0 & "" _
& "WHERE (((Assay.[assay_repeat])= " & 1 & "));"
DoCmd.RunSQL sqlupdate
You have an extra double quote and are missing a couple of spaces - try it like this:
Dim sqlupdate As String
sqlupdate = "UPDATE Assay" _
& " SET Assay.assay_repeat = " & 0 & " _
& " WHERE (((Assay.[assay_repeat])= " & 1 & "));"
You just missed space chars at end of the table name and before where.
Dim sqlupdate As String
sqlupdate = "UPDATE Assay " _
& "SET Assay.assay_repeat = " & 0 & " " _
& "WHERE (((Assay.[assay_repeat])= " & 1 & "));"
Here is a great way to convert a SQL string to VBA code.
Creating the form
The form just needs two text boxes, and a command button. SQL statements can be quite long, so you put the text boxes on different pages of a tab control.
Create a new form (in design view.)
Add a tab control.
In the first page of the tab control, add a unbound text box.
Set its Name property to txtSql.
Increase its Height and Width so you can see many long lines at once.
In the second page of the tab control, add another unbound text box.
Name it txtVBA, and increase its height and width.
Above the tab control, add a command button.
Name it cmdSql2Vba.
Set its On Click property to [Event Procedure].
Click the Build button (...) beside this property.
When Access opens the code window, set up the code like this:
Private Sub cmdSql2Vba_Click()
Dim strSql As String
'Purpose: Convert a SQL statement into a string to paste into VBA code.
Const strcLineEnd = " "" & vbCrLf & _" & vbCrLf & """"
If IsNull(Me.txtSQL) Then
Beep
Else
strSql = Me.txtSQL
strSql = Replace(strSql, """", """""") 'Double up any quotes.
strSql = Replace(strSql, vbCrLf, strcLineEnd)
strSql = "strSql = """ & strSql & """"
Me.txtVBA = strSql
Me.txtVBA.SetFocus
RunCommand acCmdCopy
End If
End Sub
http://allenbrowne.com/ser-71.html
I recommend you use Recordsets.
Private Sub Update_My_Records(Parent As Object)
Dim Data_Recset As Object
Dim Parent_Reference As Object
Set Data_Recset = Parent_Reference.Application.DBEngine.Workspaces(0).Databases(0).OpenRecordset("SELECT * FROM Assay WHERE assay_repeat = " & 0 & ";", DB_OPEN_DYNASET)
Data_Recset.MoveLast
Data_Recset.MoveFirst
Data_Recset.Edit
Data_Recset.Fields("assay_repeat") = 1
Data_Recset.Update
Data_Recset.Close
Set Data_Recset = Nothing
End Sub
assumptions
Parent has reference to Access.Application. (I usually pass: Form.Module.Parent reference to Sub/Function)
the table or query "Assay" already exists.
You only need to update 1 row at a time
But if you want to use Queries In Your Form:
Private Sub Query_Definition_Update()
Dim Obj_Qdef As Object
Dim Query_Name As String
Query_Name = "Q_Assay"
Me.Form.Application.DBEngine.Workspaces(0).Databases(0).QueryDefs.Refresh
Set Obj_Qdef = Me.Form.Application.DBEngine.Workspaces(0).Databases(0).QueryDefs(Query_Name)
Obj_Qdef.SQL = Query_Update(1)
Debug.Print Obj_Qdef.SQL
Obj_Qdef.Execute
''When finished updating
Obj_Qdef.Close
Set Obj_Qdef = Nothing
End Sub
'------------------------------------------------------------'
Private Function Query_Update(New_Value as Integer) As String
Query_Update = "UPDATE Assay" & _
" SET Assay.assay_repeat = " & 0 & "" & _
" WHERE (((Assay.[assay_repeat])= " & New_Value & "));"
End Sub

Code to show a DataGridView works only if I run another sub before

I wrote a code to show/hide content of a certain DataTable into a DataGridView.
DataGridView appears and disappears when I click a button.
I don't get errors but nothing is shown.
But if I click another button (who shows another form) and then go back to the main form, the code works. (??!!??)
I wasn't able to understand what (in the 2nd code) makes the first code to work: it seems there aren't connections between two codes.
EDIT
I made some tests and I can add more informations:
I added a button to show (in a msgbox) the DataGridView properties.
The control was correctly added and all properties are correct.
The property "Visible" is set "True" but the DataGridView is still "invisible".
I added a button that sets DGV_Tbl.Visible = False and DGV_Tbl.Visible = True
And when I click it the DataGridView appears.
But if I click Btn_ShowHideTbl again (to remove DGV) and again (to re-add DGV) DataGridView is still "invisible".
This doesn't happens when I click the button to open the second form and then I close it to go back to the first form.
In this case all works correctly.
I could solve adding DGV_Tbl.Visible = False and DGV_Tbl.Visible = True to the first code but I don't think it's a good idea.
I would like to understand the problem and solve it without "strange instructions".
EDIT 2
I noticed that also the code .AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells) doesn't work without opening the 2nd form.
On this istruction DGV_Tbl.Visible = False and DGV_Tbl.Visible = True haven't effect.
EDIT 3
I've done as in the accepted answer, but I posted another question here hoping to understand what's wrong in my code.
This is my code to show/hide DataGridView:
Private Sub Btn_ShowHideTbl_Click(sender As Object, e As EventArgs) Handles Btn_ShowHideTbl.Click
ShowHideTbl()
End Sub
Private Sub ShowHideTbl()
'Look for DGV
Dim DGV_Tbl As DataGridView = Nothing
Try
DGV_Tbl = CType(Me.Controls("DGV_Tbl"), DataGridView)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Try
'If not found I need to show data
If DGV_Tbl Is Nothing Then
If Me.CBox_ProcType.Text = "Select a Procedure" Then
MsgBox("You need To select a Procedure", vbInformation, "Unable to show table")
Exit Sub
End If
DGV_Tbl = New DataGridView
'It needs to copy data to another DataTable to show Double as Currency
Using DTemp As DataTable = New DataTable
Dim TblName As String = Me.CBox_ProcType.Text
For C As Integer = 0 To DS_All.Tables(TblName).Columns.Count - 1
DTemp.Columns.Add(DS_All.Tables(TblName).Columns(C).ColumnName, Type.GetType("System.String"))
Next
Dim Arr(DS_All.Tables(TblName).Columns.Count - 1) As String
For R As Integer = 0 To DS_All.Tables(TblName).Rows.Count - 1
For C As Integer = 0 To DS_All.Tables(TblName).Columns.Count - 1
If C = 0 Then
Arr(C) = DS_All.Tables(TblName).Rows(R)(C).ToString
Else
Arr(C) = FormatCurrency(DS_All.Tables(TblName).Rows(R)(C).ToString, 2)
End If
Next
DTemp.Rows.Add(Arr)
Next
'Working on created DataGridView
With DGV_Tbl
.Name = "DGV_Tbl"
'Add control to the Form
Me.Controls.Add(DGV_Tbl)
.DataSource = DTemp
.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells)
.RowHeadersVisible = False
.AllowUserToAddRows = False
.AllowUserToDeleteRows = False
End With
'Dispose the copied DataTable
End Using
'Resizing Form to include new DataGridView
Dim DGV_H As Integer = 0
Dim DGV_W As Integer = 0
For Each R As DataGridViewRow In DGV_Tbl.Rows
DGV_H += R.Height
Next
DGV_H += DGV_Tbl.ColumnHeadersHeight
'Add more space to include spaces between cells
DGV_H += CInt(DGV_Tbl.Rows.Count * 0.45)
For Each C As DataGridViewColumn In DGV_Tbl.Columns
DGV_W += C.Width
Next
'Add more space to include spaces between cells
DGV_W += CInt(DGV_Tbl.Columns.Count * 0.45)
DGV_Tbl.Height = DGV_H
DGV_Tbl.Width = DGV_W
'Resize the Form
Me.Height += DGV_H + 30
Me.Controls("DGV_Tbl").Location = New Point(15, Me.Height - DGV_H - 30)
'Align for currency
For x As Integer = 1 To DGV_Tbl.Columns.Count - 1
DGV_Tbl.Columns(x).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
Next
Else
'If DGV exists I need to remove it and resize the form
Dim DGV_H As Integer = DGV_Tbl.Height
DGV_Tbl.Dispose()
Me.Height -= (DGV_H + 30)
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
This is the code in the button who shows another form (and the code to close the form and go back):
Private Sub Btn_ShowSummary_Click(sender As Object, e As EventArgs) Handles Btn_ShowSummary.Click
Try
If Me.CBox_ProcType.Text = "Select a Procedure" OrElse Me.CBox_ProcValue.Text = "Select a Value" Then
MsgBox("It needs to select a Procedure and a Value",
vbInformation, "Unable to show table")
Exit Sub
End If
Summary = "...Here Some text..." & vbCrLf & Split(Me.CBox_ProcType.Text, ".")(1).Trim & vbCrLf & vbCrLf
Summary &= "...Here Some text..." & Me.CBox_ProcValue.Text & vbCrLf & vbCrLf
Dim C1Wdt% = -50
Dim C2Wdt% = TBox_TotAll.Text.Length
For R As Integer = 1 To 4
Dim CBox_Phase As CheckBox = CType(Me.TLP_Phases.Controls("CBox_Phase" & R.ToString), CheckBox)
Dim TBox_ValPh As TextBox = CType(Me.TLP_Phases.Controls("TBox_ValPh" & R.ToString), TextBox)
If CBox_Phase.Checked Then
Summary &= String.Format("{0," & C1Wdt.ToString & "} {1," & C2Wdt.ToString & "}",
CBox_Phase.Text, TBox_ValPh.Text) & vbCrLf
Dim TBox_SelVarPh As TextBox = CType(Me.TLP_Phases.Controls("TBox_SelVarPh" & R.ToString), TextBox)
If TBox_SelVarPh.Text = "" OrElse TBox_SelVarPh.Text = "€ 0,00" Then
Summary &= "...Here Some text..." & vbCrLf
Else
Dim SelVarTxt$ = If(Val(TBox_SelVarPh.Text) > 0,
"...Here Some text..." & TBox_SelVarPh.Text,
"...Here Some text..." & TBox_SelVarPh.Text.Substring(1)) & vbCrLf
Summary &= SelVarTxt
End If
End If
Next
Summary &= String.Format("{0," & C1Wdt.ToString & "} {1," & C2Wdt.ToString & "}", "", New String(CChar("_"), C2Wdt)) & vbCrLf
Summary &= String.Format("{0," & C1Wdt.ToString & "} {1," & C2Wdt.ToString & "}",
"...Here Some text...",
Me.TBox_TotPhases.Text) & vbCrLf
If Me.TBox_PrtAdg.Text <> "€ 0,00" Then
Summary &= String.Format("{0," & C1Wdt.ToString & "} {1," & C2Wdt.ToString & "}",
"...Here Some text...",
Me.TBox_PrtAdg.Text) & vbCrLf
Summary &= "...Here Some text..." & TBox_PrtRapp.Text & "...Here Some text..." & TBox_CPrt.Text & "...Here Some text..." & vbCrLf
End If
Summary &= String.Format("{0," & C1Wdt.ToString & "} {1," & C2Wdt.ToString & "}",
"...Here Some text..." & TBox_ForfPercent.Text,
Me.TBox_ForfImp.Text) & vbCrLf
Summary &= "...Here Some text..." & TBox_TotPhases.Text & ")" & vbCrLf
Summary &= String.Format("{0," & C1Wdt.ToString & "} {1," & C2Wdt.ToString & "}", "", New String(CChar("_"), C2Wdt)) & vbCrLf
Summary &= String.Format("{0," & C1Wdt.ToString & "} {1," & C2Wdt.ToString & "}",
"...Here Some text...",
Me.TBox_TotAll.Text) & vbCrLf
Me.Hide()
Me.ShowInTaskbar = False
Frm_Summary.Show()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Here the code of the back button:
Private Sub Btn_CloseNBack_Click(sender As Object, e As EventArgs) Handles Btn_CloseNBack.Click
Frm_Base.ShowInTaskbar = True
Frm_Base.Show()
Me.Close()
End Sub
I don't see any connetion between the codes (but it seems I'm wrong) please show me what I'm missing.
May I suggest another approach for your problem ?
If i were you, i would think about using a drawn datagridview, put datatable content into it before hand.
Then in the show/hide button, just switch the visibility of that datagridview along with recalculating the form size.
As for the currency column, instead of making another table, you can just populate the datatable into your datagridview, then set the format of that column into currency:
DGV_Tbl.Columns("CurrencyColumn").DefaultCellStyle.Format = "c"
More information about datagridview column formatting can be found here

Can anyone convert this VB.NET code to VBScript?

Anybody out there that can help convert this small chunk of VB.NET to VBScript, I didn't realise when I was writing my tester app that the application I was going to use it in is all VBScript =(
The code gets a table from the database, then writes a couple of lines and then the table to a tab delimited file. I understand I may have to rewrite the part with Lambda completely? I may have to start again but if anyone can do this I would be appreciative!
Private dataTable As New DataTable()
Protected Sub Page_Load(sender As Object, e As EventArgs)
PullData()
End Sub
Public Sub PullData()
'Get data from DB into a DataTable
Using conn As New SqlConnection("Server=.\sqlexpress;Database=DB;User Id=User;Password=Password;")
Using cmd As New SqlCommand("SELECT areaID as 'Pond Number', storageDescription + SPACE(1) + areaID as 'Pond Name', " & vbCr & vbLf & "case when fishWeight = 0 then 0 else 1 end as 'Pondis Used', 1 as 'Volume', " & vbCr & vbLf & "FeedDensity AS 'Feed Density',round(cast(FeedDensity * revolution as float(25)),2)/*cast as float for correct rounding*/ AS 'Feed Multiplier'," & vbCr & vbLf & "feedType as 'Feed Type', feedName as 'Feed Name', batchID AS 'FishBatchCode'" & vbCr & vbLf & vbCr & vbLf & "FROM dbo.vwStorageMASTER" & vbCr & vbLf & vbCr & vbLf & "WHERE fkLocationID = 1 AND fkStorageIndicator <> 3 ORDER BY sequenceNumber ASC", conn)
conn.Open()
Dim da As New SqlDataAdapter(cmd)
da.Fill(dataTable)
End Using
End Using
'Output tab-delimited
Dim delim As String = vbTab
Dim sb = New StringBuilder()
sb.AppendLine("Trafalgar Master File" & vbCr & vbLf & vbCr & vbLf)
sb.AppendLine(String.Join(delim, "Number of Ponds: ", dataTable.Rows.Count.ToString() & vbCr & vbLf & vbCr & vbLf))
sb.AppendLine(String.Join(delim, dataTable.Columns.Cast(Of DataColumn)().[Select](Function(arg) arg.ColumnName)))
For Each dataRow As DataRow In dataTable.Rows
sb.AppendLine(String.Join(delim, dataRow.ItemArray.[Select](Function(arg) arg.ToString())))
Next
'Prompt user to download tab-delimited file
Dim FileName As String = "test.xls"
Dim response As System.Web.HttpResponse = System.Web.HttpContext.Current.Response
response.ClearContent()
response.Clear()
response.ContentType = "text/plain"
response.AddHeader("Content-Disposition", "attachment; filename=" & FileName & ";")
response.Write(sb.ToString())
response.Flush()
response.[End]()
End Sub
While VB.Net and VBScript share a similar syntax, the objects that they use are entirely different animals. Vbscript has no knowledge of System.Web, System.Data, StringBuilder, etc. Instead, you might want to look into the VB6 syntax and the late bound CreateObject syntax to create AdoDb objects.
This was how I rewrote it for my application. In the end I basically started again but it's result is pretty much the same;
<%#LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<%Response.Buffer = True%>
<!--#include file="Conn/conn.asp" -->
<%
Call DownloadFile()
Private Sub DownloadFile()
Dim Comm
Dim rst
Dim delim
delim = vbTab
response.Clear
set rst = Server.CreateObject("ADODB.Recordset")
rst.ActiveConnection = MM_Conn_STRING
rst.Open "Select COUNT(*) from vwTrafalgarMasterFile"
'Write titles
Response.Write("Trafalgar Master File" & vbcrlf & vbcrlf)
Response.Write("Number of Ponds: " & rst.Fields(0).Value & vbcrlf & vbcrlf)
If rst.State = 1 Then rst.Close 'Used 1 instead of AdStateOpen as this seemed to cause an error
rst.Open "Select * from vwTrafalgarMasterFile"
'Write headers
If Not rst.EOF Then
For Each fld In rst.Fields
Response.Write(fld.Name & delim)
Next
Response.Write vbcrlf
Else
Response.Write("There was a problem retrieving data or no data could be retrieved")
Response.End
Exit sub
End if
'Write rows
With rst
.MoveFirst
Do Until .EOF
For Each fld In rst.Fields
Response.Write(fld.Value & delim)
Next
Response.Write vbcrlf
.Movenext
Loop
End With
Dim FileName
FileName = "TrafalgarMasterFile.xls"
response.ContentType = "text/plain"
response.AddHeader "Content-Disposition", "attachment; filename=" + FileName + ";"
response.Flush
response.End
'Clean up
adoCMD.Close
Set Comm = Nothing
Set rst = Nothing
Set fld = Nothing
End Sub
%>

Data type mismatch in VB 2008

Good day guys, I have a question. When I try to use this piece of code in my program which will add a supplier to the database, I encounter data type mismatch error. As far as I know, the status of the supplier creates the error.
How would I store the values of the radio buttons named radActive and radInactive in the database? Should I use Boolean or a String? I am using Microsoft Access as my database and the field of Status is set to Yes/No.
Here's the code.
Public Sub SupplierInsertData()
Dim conn As OleDb.OleDbConnection
Dim cmd As OleDb.OleDbCommand
Dim SupplierType As String
Dim Status As Boolean
'Check for supplier type
If frmDatabaseSupplier.radLocal.Checked = True Then
SupplierType = "Local"
ElseIf frmDatabaseSupplier.radForeign.Checked = True Then
SupplierType = "Foreign"
End If
'Check for supplier status
If frmDatabaseSupplier.radActive.Checked = True Then
Status = True
ElseIf frmDatabaseSupplier.radInactive.Checked = True Then
Status = False
End If
'For inserting of data in the database.
Dim cmdString As String = "INSERT INTO Supplier(SupplierLastName, SupplierFirstName, SupplierMiddleInitial, " & _
"SupplierCompany, SupplierType, SupplierStreetAddress, SupplierCity, SupplierContactNumber, SupplierEmail, " & _
"Status)" & _
"VALUES('" & frmDatabaseSupplier.txtSupplierLastName.Text & "','" & frmDatabaseSupplier.txtSupplierFirstName.Text & "','" & frmDatabaseSupplier.txtSupplierMiddleInitial.Text & "','" _
& frmDatabaseSupplier.txtSupplierCompany.Text & "','" & SupplierType & "', '" & frmDatabaseSupplier.txtSupplierStreetAddress.Text & "','" & frmDatabaseSupplier.txtSupplierCity.Text & "','" _
& frmDatabaseSupplier.txtSupplierContactNumber.Text & "','" & frmDatabaseSupplier.txtSupplierEmail.Text & "','" & Status & "')"
conn = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ProjectAnalysisSystem.accdb")
cmd = New OleDb.OleDbCommand(cmdString, conn)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Sub
Thank you!
Try to change the last part of your code.
You should use parameters to pass the values of your textbox or vars to the database engine.
And don't forget to encapsulate the disposable objects like OleDbConnection in a using statement.
Dim cmdString As String = "INSERT INTO Supplier(SupplierLastName, SupplierFirstName, SupplierMiddleInitial, " & _
"SupplierCompany, SupplierType, SupplierStreetAddress, SupplierCity, SupplierContactNumber, SupplierEmail, " & _
"Status)" & _
"VALUES(#supplierName, #supplierFirst, #supplierMiddle, #supplierCo, #supplierType, #supplierStreet, #supplierCity, " & _
"#supplierContact, #supplierMail, #status)"
Using conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ProjectAnalysisSystem.accdb")
Dim cmd As OleDbCommand = New OleDb.OleDbCommand(cmdString, conn))
cmd.Parameters.AddWithValue("#supplierName", frmDatabaseSupplier.txtSupplierLastName.Text)
cmd.Parameters.AddWithValue("#supplierFirst", frmDatabaseSupplier.txtSupplierFirstName.Text)
cmd.Parameters.AddWithValue("#supplierMiddle", frmDatabaseSupplier.txtSupplierMiddleInitial.Text)
cmd.Parameters.AddWithValue("#supplierCo", frmDatabaseSupplier.txtSupplierCompany.Text )
cmd.Parameters.AddWithValue("#supplierType", SupplierType)
cmd.Parameters.AddWithValue("#supplierStreet", frmDatabaseSupplier.txtSupplierStreetAddress.Text)
cmd.Parameters.AddWithValue("#supplierCity", frmDatabaseSupplier.txtSupplierCity.Text)
cmd.Parameters.AddWithValue("#supplierContact", frmDatabaseSupplier.txtSupplierContactNumber.Text)
cmd.Parameters.AddWithValue("#supplierMail", frmDatabaseSupplier.txtSupplierEmail.Text)
cmd.Parameters.AddWithValue("#status", Status) '<- Here the status var is correctly identified as a boolean, not as a string
conn.Open()
cmd.ExecuteNonQuery()
End Using
You have a data type mismatch error because your INSERT statement attempts to store a string value for the Status field whose data type is Yes/No.
This isn't really a VB.Net problem. You would get the very same error from Access' db engine if you were attempting the same thing from VBA. This is the output from the VBA procedure below.
INSERT INTO Supplier (Status)
VALUES('True')
Error -2147217913 (Data type mismatch in criteria expression.)
The procedure ...
Public Sub Ju_chan()
Dim cmdString As String
Dim Status As Boolean
Dim strMsg As String
On Error GoTo ErrorHandler
Status = True
cmdString = "INSERT INTO Supplier (Status)" & vbCrLf & _
"VALUES('" & Status & "')"
Debug.Print cmdString
CurrentProject.Connection.Execute cmdString
ExitHere:
On Error GoTo 0
Exit Sub
ErrorHandler:
strMsg = "Error " & Err.Number & " (" & Err.Description _
& ")"
Debug.Print strMsg
GoTo ExitHere
End Sub
Please understand this is not intended to steer you away from using parameters. I only wanted to clarify why you're getting that error.

.NextResult() method does gives an error that states that no data is present

Can you check my coding and let me know what I'm doing wrong?
I'm trying to use the .NextResult() method of a DataReader but I get an error that no data is present.
The 1st query returns a value but the 2nd query is the problem.
Dim strSqlStatement As String = "Select Count(*) As TotalRows " & _
"From Parents " & _
"Where (FatherName = #SearchValue " & _
" Or MotherName = #SearchValue);"
strSqlStatement = strSqlStatement & "Select FatherName, MotherName " & _
"From Parents " & _
"Where (FatherName = #SearchValue " & _
" Or MotherName = #SearchValue)"
' Set up the sql command and lookup the parent.
'----------------------------------------------
Using objSqlCommand As SqlCommand = New SqlCommand(strSqlStatement, ObjConnection)
With objSqlCommand
' Add SqlParameters to the SqlCommand.
'-------------------------------------
.Parameters.Clear()
.Parameters.AddWithValue("#SearchValue", TextBoxParentsName.Text)
' Open the SqlConnection before executing the query.
'---------------------------------------------------
Try
ObjConnection.Open()
' Execute the query to see if the parents are in the database.
'-------------------------------------------------------------
' Display the parent info.
'-------------------------
Dim reader As SqlDataReader = .ExecuteReader()
reader.Read()
Dim countOfRows = reader("TotalRows")
If countOfRows = 1 Then
reader.NextResult()
TextBoxParentsName.Text = reader("FatherName").ToString()
LabelBothParents.Text = "Father: " & TextBoxParentsName.Text & " Mother: " & reader("MotherName")
End If
Catch exErrors As Exception
MessageBox.Show("Sorry, there was an error. Details follow: " & _
vbCrLf & vbCrLf & exErrors.Message, _
"Error")
TextBoxParentsName.Focus()
Finally
blnDisableParentIdTextChanged = False
ObjConnection.Close()
End Try
End With ' objSqlCommand
End Using ' objSqlCommand
Found the missing statement:
I needed to add:
reader.Read()
after the reader.NextResult this area of coding:
If countOfRows = 1 Then
reader.NextResult()
reader.Read() ' This is what I needed to add.
TextBoxParentsName.Text = reader("FatherName").ToString()
LabelBothParents.Text = "Father: " & TextBoxParentsName.Text & " Mother: " & reader("MotherName")
End If
I hope this helps someone who gets stuck like I did.