Visual Studio: cannot resolve connect identifier - sql

I am able to compile to run the code, but when the form is out and I enter value to be searched, it gives the error stated in the title. This is the code:
Public Class Form1
Private Sub Search_Click(sender As Object, e As EventArgs) Handles Search.Click
Dim myConn As New OleDb.OleDbConnection
Dim myString As String
Dim myArg As String
Dim mysql As String
' Connect to dataset
myString = "Provider=msdaora;data source=orcl;User Id=XXXXXX;Password=XXXXX"
myConn.ConnectionString = myString
' Get the argument
myArg = TextBox1.Text
mysql = "select * from Orders where lastname like '%" + myArg + "%'"
Try
myConn.Open()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
'Create data adapter
Dim myDataadapter As New OleDb.OleDbDataAdapter(mysql, myConn)
' Create a dataset
Dim myDs As New DataSet
' Fill the dataset
myDataadapter.Fill(myDs, "customer")
' Display ADO data.....
DataGridView1.DataSource = myDs
DataGridView1.DataMember = "customer"
End Sub
End Class

Related

How to select an excel data Table using a drop downlist value

I am working on an application that uses excel files as its data source. I would love the DataGridView to populate with the columns of a sheet when a worksheet name is selected from the drop down list.
Here is what I have tried doing:
Imports System.Data.OleDb
Public Class Form101
Public cn As New OleDbConnection
Public cm As New OleDbCommand
Public da As OleDbDataAdapter
Dim comb As String
Public dt As New DataTable
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Comb1.SelectedIndexChanged
comb = Comb1.SelectedText
End Sub
Public Sub FillDataGridView(ByVal Query As String)
da = New OleDbDataAdapter(Query, cn)
dt.Clear()
da.Fill(dt)
With DataGridView1
.DataSource = dt
.Columns(0).HeaderText = "Date"
.Columns(1).HeaderText = "Qty brought"
.Columns(2).HeaderText = "Qty sold"
.Columns(3).HeaderText = "Goods balance"
.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
End With
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
cn.ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\toojah app\Stock card.xls; Extended Properties= Excel 8.0;"
cn.Open()
FillDataGridView("select * FROM ['" & comb & "'] ")
End Sub
End Class
Try something like this. The first function will collect all of the columns and records in your excel file and place it into a datatable. Then If you wanted to add additional columns to the datable you can do it in the Public Sub CreateDataGridView. This has been tested and works.
Friend Shared Function BuildDatatable () as datatable
Dim dt As New DataTable
Dim Conn As System.Data.OleDb.OleDbConnection
Dim cmd As System.Data.OleDb.OleDbDataAdapter
dim MyFile as string = "C:\toojah app\Stock card.xls"
Conn = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + MyFile + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1';")
Conn.Open()
Dim dtSheets As DataTable = Conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
listSheet.Add(drSheet("TABLE_NAME").ToString())
cmd = New System.Data.OleDb.OleDbDataAdapter("select * from [" & drSheet("TABLE_NAME").ToString() & "]", Conn)
cmd.TableMappings.Add("Table", "Net-informations.com")
cmd.Fill(dt)
Conn.Close()
Next
Return dt
Catch ex As Exception
Return Nothing
End Try
End Function
'This is used to pass the function datatable as a dt to then pass to the public sub as shown below.
Dim dt As DataTable = BuildDatatable
Public Sub CreateDataGridView(dt)
Dim newColumn As New Data.DataColumn("ComeColumnName", GetType(System.String))
newColumn.DefaultValue = "YourValues"
dt.Columns.Add(newColumn)
DataGridView1.DataSource = dt
End Sub

Checking a PIN number is correct according to it's card number

I'm currently working on an assignment for college that I'm really stuck on. I have to create an application to simulate an ATM machine using Visual Basic 2010. I'm currently stuck trying to check whether the PIN number entered in the text box is correct for the card number selected in the combo box. If the user enters the PIN incorrectly three times, the card is confiscated. I am getting an error message at the moment saying "Object variable or With block variable not set". Below is the code I have written:
Imports System.Data.OleDb
Public Class PinEntry
Public connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\Users\ben\Documents\Programming\Year 2\Visual Studio\Assignment2\BankOfGlamorgan\EDP2011-BoG.mdb"
Friend connectionBG As New OleDbConnection
Dim ds As New DataSet
Dim da As New OleDbDataAdapter
Dim commandCardNumber As New OleDbCommand()
Dim dr As OleDbDataReader
Dim pinErrorCount As Integer
Dim ATMCardsBindingSource As New BindingSource
Dim SqlCommandCheckPIN As New OleDbCommand
Dim SqlCommandConfiscate As New OleDbCommand
Private Sub PinEntry_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connectionBG.ConnectionString = connectionString
commandCardNumber.Connection = connectionBG
commandCardNumber.CommandType = CommandType.Text
commandCardNumber.CommandText = "SELECT cardNumber FROM ATMCards"
Try
connectionBG.Open()
da.SelectCommand = commandCardNumber
da.Fill(ds, "ATMCards")
cmbCardNumber.DataSource = ds.Tables("ATMCards")
cmbCardNumber.DisplayMember = "cardNumber"
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
connectionBG.Close()
End Try
End Sub
Private Sub btnEnterPin_Click(sender As Object, e As EventArgs) Handles btnEnterPin.Click
Try
Me.connectionBG.Open()
Dim PIN As String
Dim cardNo As String
PIN = Me.txtPIN.Text
cardNo = Me.ATMCardsBindingSource.Current("cardNumber")
Me.SqlCommandCheckPIN.Parameters("#PIN").Value = PIN
Me.SqlCommandCheckPIN.Parameters("#cardNumber").Value = cardNo
Dim dr As OleDbDataReader = Me.SqlCommandCheckPIN.ExecuteReader()
If dr.HasRows And pinErrorCount <= 2 Then
My.Forms.Menu.ShowDialog()
dr.Close()
pinErrorCount = 0
txtPIN.Text = ""
ElseIf pinErrorCount = 2 Then
dr.Close()
MessageBox.Show("PIN Entered Incorrectly Three Times Card Now Confiscated", "Card Taken", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
cardNo = Me.ATMCardsBindingSource.Current("cardNumber")
Me.SqlCommandConfiscate.Parameters("#cardNumber").Value = cardNo
Me.SqlCommandConfiscate.ExecuteNonQuery()
Else
pinErrorCount = pinErrorCount + 1
MessageBox.Show("Incorrect PIN Please Try Again.", "Incorrect PIN", MessageBoxButtons.OK, MessageBoxIcon.Error)
txtPIN.Text = ""
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
Me.connectionBG.Close()
End Try
End Sub
End Class
Updated code below:
Imports System.Data.OleDb
Public Class PinEntry
Public connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\Users\ben\Documents\Programming\Year 2\Visual Studio\Assignment2\BankOfGlamorgan\EDP2011-BoG.mdb"
Friend connectionBG As New OleDbConnection
Dim ds As New DataSet
Dim da As New OleDbDataAdapter
Dim commandCardNumber, commandPinNumber As New OleDbCommand()
Dim dr As OleDbDataReader
Dim pinErrorCount, cardNumber, PIN As Integer
Dim oForm As Menu
Dim userInput As String
Private Sub PinEntry_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connectionBG.ConnectionString = connectionString
commandCardNumber.Connection = connectionBG
commandCardNumber.CommandType = CommandType.Text
commandCardNumber.CommandText = "SELECT cardNumber FROM ATMCards"
commandPinNumber.Connection = connectionBG
commandPinNumber.CommandType = CommandType.Text
commandPinNumber.CommandText = "SELECT PIN FROM ATMCards WHERE cardNumber = ?"
Try
connectionBG.Open()
da.SelectCommand = commandCardNumber
da.Fill(ds, "ATMCards")
cmbCardNumber.DataSource = ds.Tables("ATMCards")
cmbCardNumber.DisplayMember = "cardNumber"
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
connectionBG.Close()
End Try
End Sub
Private Sub btnEnterPin_Click(sender As Object, e As EventArgs) Handles btnEnterPin.Click
cardNumber = Convert.ToInt16(cmbCardNumber.Text)
commandPinNumber.Parameters.Add(New OleDbParameter())
commandPinNumber.Parameters(0).Value = cardNumber
Try
connectionBG.Open()
dr = commandPinNumber.ExecuteReader()
While dr.Read()
PIN = dr.Item("PIN").ToString
End While
dr.Close()
If PIN = userInput Then
MsgBox("Correct PIN")
Else
MsgBox("Incorrect PIN")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
connectionBG.Close()
End Try
End Sub
Private Sub txtPIN_TextChanged(sender As Object, e As EventArgs) Handles txtPIN.TextChanged
userInput = txtPIN.Text
End Sub
End Class
OleDBCOmmand objects are typically used in a more disposable way than as module level variables. In order to work, they also need a SQL string and a Connection object associated with them. Ex:
Dim sql As String = "SELECT etc etc etc WHERE something = ?"
Using cmd As New OleDbCommand(Sql, dbCon)
cmd.Parameters.AddWithValue("#p1", myVar)
cmd.Parameters.AddWithValue("#p2", myVar)
Dim rdr As OleDbDataReader = cmd.ExecuteReader
If rdr.HasRows Then
' do something interesting
End If
End Using
Here, both the SQL and DB Connection are associated with the Command Object when it is created. The Using block assures it is properly disposed of when we are done with it.
Also, OleDbCommand objects do not support named parameters. Usually, it just ignores them. The right way for Paramters is shown (ie AddWithValue) where you replace each ? placeholder in the SQL string in order with the actual value. Do be sure the data type matches. If PIN is a number, you must add a number, not Text.
For the SQL, you are testing the PIN entered against a card number, so those are the param values. Depending on how you construct the SQL you can either see if the PIN in the DB matches the one they gave OR just see if you get any rows back.

how to suplay data in vb net the dataset with stored procedure

I made code vb net, to can display in my form , I call data using dataset, my coding like below
Public Function GetTableRow(ByVal strsql As String) As DataSet
Dim conn As New SqlConnection
Dim sDa As New SqlDataAdapter(strsql, conn)
Dim ds As New DataSet
Try
sDa.Fill(ds)
Catch ex As Exception
End Try
sDa.Dispose()
Return ds
End Function
Private Sub CmRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmRefresh.Click
Dim ds As New DataSet
Dim conn = "server='server'; database='database'; user=user;password='password';"
Dim strsql As String = "exec spSPDMonStockProductHarian '" & 230 & "'"
ds = conn.GetTableRow(strsql)
With Listdata
.DataSource = ds.Tables(0)
End With
Koneksi.Close()
Koneksi.Close()
End Sub
My problem when I execute this program, error message
"Public member 'Function' on type 'String' not found."
I didn't get what the problem , so any solution will appreciate!!
You should try like this:
Private Sub CmRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmRefresh.Click
Dim ds As New DataSet
Dim conn As String = "server='server'; database='database'; user=user;password='password';"
Dim strsql As String = "exec spSPDMonStockProductHarian '" & 230 & "'"
ds = GetTableRow(strsql)
If ds.Tables.Count > 0 Then
With Listdata
.DataSource = ds.Tables(0)
End With
Else
MessageBox.Show("Dataset is empty")
End If
Koneksi.Close()
Koneksi.Close()
End Sub
The changed i made here:
Dim conn As String
and
ds = GetTableRow(strsql)
Basically, GetTableRow is your custom function it is not defined inside class string.

Listbox Database

Okay, so for a project I'm not allowed to use Datagridview and instead I'll have to use a Listbox to display data from a database when it is searched for. I'll link my code below, could anyone please tell me how I can change this code to suit a listbox. I'm a noob to programming so if I've made any obvious mistakes please forgive me
Imports System.Data
Imports System.Data.OleDb
Public Class frmUserList
Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
Me.Close()
End Sub
Private Sub Load_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
'try catch block is used to catch the error
Try
'get connection string declared in the Module1.vb and assing it to conn variable
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT user_id, last_name + ', ' + first_name + ' ' + mid_name as name FROM users where last_name + ', ' + first_name + ' ' + mid_name like '%" & Me.txtSearch.Text & "%' or [first_name] = '" & Me.txtSearch.Text & "'"
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.dtgResult.DataSource = dt
If dt.Rows.Count = 0 Then
MsgBox("No record found!")
End If
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Load_Record()
End Sub
Private Sub dtgResult_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtgResult.DoubleClick
If Me.dtgResult.SelectedRows.Count > 0 Then
Dim frm As New frmMarkSeat
frm.txtFname.Tag = Me.dtgResult.Item(0, Me.dtgResult.CurrentRow.Index).Value
frm.ShowDialog()
frm = Nothing
End If
End Sub
End Class
Give this a try using SQLDataReader: (untested code, just wrote out of hand).
'start here
conn.Connection.Open()
Dim sqlDR As SqlDataReader
Dim colValue As String
sqlDR = conn.ExecuteReader
While sqlDR.Read
colValue = (sqlDR.GetValue(0)).ToString
ItemlistBox.Items.Add(colValue)
ItemlistBox.Sorted = True
End While
conn.Connection.Close()
Or you can keep using your current objects, with additional object DataSet and populate the listbox.
Dim dtset As New DataSet
Dim da As New OleDbDataAdapter
da.Fill(dtset)
ItemListBox.DataSource = dtset
ItemListBox.DisplayMember = "ColName"

how to use recordset movelast

i need help for the code that i can use old rs.movelast to vb.net 2010..
any simple way to query my record that automatic select the last..
here is my connection sample i just call it only in any form..///
Public Function ExecuteSQLQuery(ByVal SQLQuery As String) As DataTable
Try
Dim sqlCon As New OleDbConnection(CnString)
Dim sqlDA As New OleDbDataAdapter(SQLQuery, sqlCon)
Dim sqlCB As New OleDbCommandBuilder(sqlDA)
sqlDT.Reset() ' refresh
sqlDA.Fill(sqlDT)
Catch ex As Exception
MsgBox("Error : " & ex.Message)
End Try
Return sqlDT
End Function
sqlDT.rows(sqlDT.rows.count-1) will be the last record of your DataTable sqlDT. sqlDT.rows.count-1 will return you the last index of the rows in the filled table. Hope it will help you. Thanks
Imports System.Data.OleDb
Public Class Form1
Public CnString As String = "Provider=SQLOLEDB;Data Source=HP-PC\SQLEXPRESS;Persist Security Info=True;Password=sa;User ID=sa;Initial Catalog=Accounts"
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ssql As String = "Select * from TBL_Access"
Dim dt As DataTable
dt = ExecuteSQLQuery(ssql)
TextBox1.Text = dt.Rows(dt.Rows.Count - 1)(0) 'Value of First Column of Last Row of DataTable dt
TextBox2.Text = dt.Rows(dt.Rows.Count - 1)(1) 'Value of Second Column of Last Row of DataTable dt
End Sub
Public Function ExecuteSQLQuery(ByVal SQLQuery As String) As DataTable
Try
Dim sqlCon As New OleDbConnection(CnString)
Dim sqlDA As New OleDbDataAdapter(SQLQuery, sqlCon)
Dim sqlCB As New OleDbCommandBuilder(sqlDA)
Dim sqlDT As New DataTable
sqlDT.Reset() ' refresh
sqlDA.Fill(sqlDT)
Return sqlDT
Catch ex As Exception
MsgBox("Error : " & ex.Message)
Return Nothing
End Try
End Function
End Class