I get error rdr is not declared - vb.net

With this line of code
using (rdr as mysqldatareader = cmd.executereader())
I get an error saying rdr is not declared. When I remove the brackets so that it becomes
Using rdr As MySqlDataReader = cmd.ExecuteReader()
I get error on this line tmpObj.No = rdr("No").ToString()saying No is not a member of the project.Form.Appdata and this line
tmpObj.Template = templa8 and Template is not a member of the project.Form.AppData. Note that I have already put this: Private FPList As New List(Of AppData) at the class level, as a member. Definitely I'm doing something wrong. Any suggestions?
'THIS NEEDS TO BE AT THE CLASS-LEVEL, AS A MEMBER
'Private FPList As New List(Of AppData)
Public Class AppData
Public Sub Update()
RaiseEvent OnChange()
End Sub
Public Event OnChange()
Public FPList As New List(Of AppData)
Public IsEventHandlerSucceeds As Boolean = True
Public IsFeatureSetMatched As Boolean = False
Public FalseAcceptRate As Integer = 0
Public Sub Update()
RaiseEvent OnChange()
End Sub
Public Event OnChange()
Public FPList As New List(Of AppData)
End Class
Private Sub Me_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles MyBase.Load
Init()
StartCapture()
Dim sql As String = "SELECT * FROM new_case_file"
Using conn As New MySqlConnection("**** "), _
cmd As New MySqlCommand(sql, conn)
conn.Open()
Using (rdr As MySqlDataReader = cmd.ExecuteReader())
FPList.Clear()
While (rdr.Read())
Dim tmpObj As New AppData
tmpObj.No = rdr("No").ToString()
Dim fpBytes As Byte() = rdr("FingerPrint")
Using MemStream As New IO.MemoryStream(fpBytes)
Dim templa8 As New DPFP.Template()
templa8.DeSerialize(MemStream)
tmpObj.Template = templa8
End Using
FPList.Add(tmpObj)
End While
rdr.Close()
End Using
End Using
End Sub

You correct that error by adding the following to your AppData class
Private _No As String
Public Property No As String
Get
Return _No
End Get
Set(value as String)
_No = value
End Set
End Property
Private _Template As DPFP.Template
Public Property Template As DPFP.Template
Get
Return _Template
End Get
Set(value as DPFP.Template)
_Template = value
End Set
End Property
but that will not necessarily make your code work.

Related

parameter marker count incorrect

Why i am getting ERROR [HY000] parameter marker count incorrect.
I am using SQLite3 Odbc Driver on my VB.Net Project and here's my code structure.
On my DBClass
Imports System.Data.Odbc
Public Class DbClass
Private DbConnection As New OdbcConnection("DRIVER=SQLite3 ODBC Driver;Database=E:\VB.NET Projects\MyBeDb.db;LongNames=0;Timeout=1000;NoTXN=0; SyncPragma=NORMAL;StepAPI=0;")
Private DbCommand As New OdbcCommand
Private DbDataAdapter As New OdbcDataAdapter
Private DbParameter As New List(Of OdbcParameter)
Private DbRecordCount As Integer = 0
Private DbDataTable As DataTable
Sub ExecuteQuery(_Query As String)
DbRecordCount = 0
DbConnection.Open()
DbCommand = New OdbcCommand(_Query, DbConnection)
DbParameter.ForEach(Sub(p) DbCommand.Parameters.Add(p))
DbParameter.Clear()
DbDataTable = New DataTable
DbDataAdapter = New OdbcDataAdapter(DbCommand)
DbRecordCount = DbDataAdapter.Fill(DbDataTable)
If DbConnection.State = ConnectionState.Open Then DbConnection.Close()
End Sub
Sub AddParameters(_Name As String, _Value As Object)
Dim NewParam As New OdbcParameter(_Name, _Value)
DbParameter.Add(NewParam)
End Sub
Sub Authenticate(_Username As String, _Password As String)
AddParameters("Un", _Username)
AddParameters("Pw", _Password)
ExecuteQuery("SELECT * FROM UserAccounts WHERE [Username] LIKE #Un AND [Password] LIKE #Pw;")
End Sub
End Class
On Button Click
Private myDb As New DbClass
Private Sub Login_Click(sender As Object, e As EventArgs) Handles Login.Click
Try
myDb.Authenticate("Admin", "Password")
Catch ex As Exception
MsgBox(ex.Message & Environment.NewLine & Environment.NewLine & ex.StackTrace)
End Try
End Sub
I tried using ? instead of # and it didn't throw any exception message if i mistype a username and password.

How do i get specific columns from datatables to fill a constructor with?

I got 2 DataTables which i open with a openFileDialog with the following columnnames: "UANR", "KostenArt", "Ueberbegriff", "Benennung", "Anzahl", "Einheit", "Einzelkosten", "SummenCode", "Kst", "AufPos", "Summenkosten".
But i only need the values for the following ones,
ReadOnly Property KostenArt As String
ReadOnly Property UANR As String
ReadOnly Property Ueberbegriff As String
ReadOnly Property Benennung As String
ReadOnly Property Anzahl As Double
ReadOnly Property Einheit As String
ReadOnly Property Einzelkosten As Double
ReadOnly Property Gesamtmenge As Integer
ReadOnly Property Summencode As String
to fill the constructor with and make a list of objects with this method:
Private Function ConvertDataTableToListOfISAACService(dt As DataTable, lst As List(Of ISAACService)) As List(Of ISAACService)
For Each row As DataRow In dt.Rows
Dim ISAAC As New ISAACService(row(KostenArt).ToString, row(UANR).ToString, row(Ueberbegriff).ToString, row(Benennung).ToString, CDbl(row(Anzahl)), row(Einheit).ToString, CDbl(row(Einzelkosten)), CInt(row(Gesamtmenge)), row(Summencode).ToString)
lst.Add(ISAAC)
Next
Return lst
End Function
Here is how i put in the datatables:
Private Sub btnDatei1_Click(sender As Object, e As EventArgs) Handles btnDatei1.Click
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
If File.Exists(OpenFileDialog1.FileName) Then
dt1 = FileGenerator.ReadFromProtectedFile(OpenFileDialog1.FileName)
dgv1.DataSource = dt1
ConvertDataTableToListOfISAACService(dt1, lst1)
End If
End If
End Sub
Private Sub btnDatei2_Click(sender As Object, e As EventArgs) Handles btnDatei2.Click
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
dt2 = FileGenerator.ReadFromProtectedFile(OpenFileDialog1.FileName)
dgv2.DataSource = dt2
ConvertDataTableToListOfISAACService(dt2, lst2)
End If
End Sub
The full code:
Public Class MainForm
Private Const KostenArt As String = "KostenArt"
Private Const UANR As String = "UANR"
Private Const Ueberbegriff As String = "Ueberbegriff"
Private Const Benennung As String = "Benennung"
Private Const Anzahl As String = "Anzahl"
Private Const Einheit As String = "Einheit"
Private Const Einzelkosten As String = "Einzelkosten"
Private Const Gesamtmenge As String = "Gesamtmenge"
Private Const Summencode As String = "Summencode"
Public dt1, dt2 As DataTable
Public lst1, lst2 As List(Of ISAACService)
Private Sub btnDatei1_Click(sender As Object, e As EventArgs) Handles btnDatei1.Click
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
If File.Exists(OpenFileDialog1.FileName) Then
dt1 = FileGenerator.ReadFromProtectedFile(OpenFileDialog1.FileName)
dgv1.DataSource = dt1
ConvertDataTableToListOfISAACService(dt1, lst1)
End If
End If
End Sub
Private Sub btnVergleich_Click(sender As Object, e As EventArgs) Handles btnVergleich.Click
'CompareDataTables()
End Sub
Private Sub btnDatei2_Click(sender As Object, e As EventArgs) Handles btnDatei2.Click
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
dt2 = FileGenerator.ReadFromProtectedFile(OpenFileDialog1.FileName)
dgv2.DataSource = dt2
ConvertDataTableToListOfISAACService(dt2, lst2)
End If
End Sub
Private Sub CompareDataTables(ByRef lst1 As List(Of ISAACService), ByRef lst2 As List(Of ISAACService))
End Sub
Private Function ConvertDataTableToListOfISAACService(dt As DataTable, lst As List(Of ISAACService)) As List(Of ISAACService)
Try
For Each row As DataRow In dt.Rows
Dim ISAAC As New ISAACService(row(KostenArt).ToString, row(UANR).ToString, row(Ueberbegriff).ToString, row(Benennung).ToString, CDbl(row(Anzahl)), row(Einheit).ToString, CDbl(row(Einzelkosten)), CInt(row(Gesamtmenge)), row(Summencode).ToString)
lst.Add(ISAAC)
Next
Return lst
Catch ex As System.ArgumentException
End Try
End Function
End Class
Think the problem is in the way you've declared lst and the signature of the ConvertDataTableToListOfISAACService method. Try something like this maybe.
Private Function ConvertDataTableToListOfISAACService(dt As DataTable) As List(Of ISAACService)
Dim lst As Zew List(Of ISAACService)
Try
For Each row As DataRow In dt.Rows
Dim ISAAC As New ISAACService(row(KostenArt).ToString, row(UANR).ToString, row(Ueberbegriff).ToString, row(Benennung).ToString, CDbl(row(Anzahl)), row(Einheit).ToString, CDbl(row(Einzelkosten)), CInt(row(Gesamtmenge)), row(Summencode).ToString)
lst.Add(ISAAC)
Next
Return lst
Catch ex As System.ArgumentException
'Do something with the exception, here.
End Try
End Function
It's also more than possible something is throwing an exception, but with your empty catch block, it's not being reported

Exception message when trying to load data to DataGridView

Imports System.Data.SqlClient
Public Class SQLCONTROL
Private DBcon As New SqlConnection("Data Source=DESKTOP-DQ7NOIF\SQLEXPRESS;Integrated Security=True")
Private DBcom As New SqlCommand
Public DBDA As SqlDataAdapter
Public DBDT As DataTable
Public Params As New List(Of SqlParameter)
Public RecordCount As Integer
Public Exception As String
Public Sub New()
End Sub
Public Sub New(ConnctionString As String)
DBcon = New SqlConnection(ConnctionString)
End Sub
Public Sub ExecQuery(Query As String)
RecordCount = 0
Exception = ""
Try
DBcon.Open()
DBcom = New SqlCommand(Query, DBcon)
Params.ForEach(Sub(p) DBcom.Parameters.Add(p))
DBDT = New DataTable
DBDA = New SqlDataAdapter(DBcom)
RecordCount = DBDA.Fill(DBDT)
Catch ex As Exception
Exception = "ExecQuery Error" & vbNewLine & ex.Message
Finally
If DBcon.State = ConnectionState.Open Then DBcon.Close()
End Try
End Sub
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New SqlParameter(Name, Value)
Params.Add(NewParam)
End Sub
Public Function HasException(Optional Report As Boolean = False) As Boolean
If String.IsNullOrEmpty(Exception) Then Return False
If Report = True Then MsgBox(Exception, MsgBoxStyle.Critical, "Exception:")
Return True
End Function
End Class
the exception message is "A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Nom d'objet 'Utilisateurs' non valide."
thanks
Many database objects (including connections and commands) expose a .Dispose method which means that they may be using unmanaged resources which need to be released. To guarantee that .Dispose is called .net provides Using...End Using.
Any errors will bubble up to the calling code where you can handle them and inform the user. After all, your class could be used in a web app or phone app where MsgBox would not work. Leave informing the user to the User Interface code.
Public Class SQLCONTROL
Private ConStr As String = "Data Source=DESKTOP-DQ7NOIF\SQLEXPRESS;Integrated Security=True"
Public Function IsUserValid(userName As String, password As String) As Boolean
Dim RetVal As Integer
Using DBcon As New SqlConnection(ConStr),
DBcom As New SqlCommand("Select Count(*) From [Utilisateurs] Where UserName = #UserName And Password = #Password;", DBcon)
DBcom.Parameters.Add("#UserName", SqlDbType.NVarChar, 50).Value = userName
DBcom.Parameters.Add("#Password", SqlDbType.NVarChar, 100).Value = password
DBcon.Open()
RetVal = CInt(DBcom.ExecuteScalar)
End Using
If RetVal = 0 Then
Return False
End If
Return True
End Function
'To return a DataTable for a DataGridView
Public Function GetCustomerOrders(Customer As String) As DataTable
Dim dt As New DataTable
Using DBcon As New SqlConnection(ConStr),
DBcom As New SqlCommand("Select * From Orders Where CustomerName = #CustomerName;", DBcon)
DBcom.Parameters.Add("#CustomerName", SqlDbType.NVarChar, 100).Value = Customer
DBcon.Open()
dt.Load(DBcom.ExecuteReader)
End Using
Return dt
End Function
End Class
Usage in Form
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim sql As New SQLCONTROL
If sql.IsUserValid("Mary", "MySecretPassword") Then
'Do something
End If
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim sql As New SQLCONTROL
DataGridView1.DataSource = sql.GetCustomerOrders("General Motors")
End Sub
Naturally, I only guessed at field names, types, and sizes. Check your database.
In a real application you would never store passwords as plain text.

Having trouble populating listview box with vendor info

When the form loads there is a combo box where you select a GL account. Once one is selected, then I click the Get Vendor button to load the vendor information. I'm having problems with the code mainly on the form.vb. I need to populate the listview box with the vendor information and I'm not sure what I did wrong. I have referenced the payables class library etc. Getting error at vendor.count on form.vb. I haven't input the database info on Payables.DB b/c I'm not sure what it yes. Thanks.
Public Class Vendor
Dim m_VendorName As Integer
Dim m_FirstName As String
Dim m_LastName As String
Dim m_City As String
Dim m_State As String
Public Sub New()
End Sub
Public Property VendorName() As String
Get
Return m_VendorName
End Get
Set(ByVal value As String)
m_VendorName = value
End Set
End Property
Public Property FirstName() As String
Get
Return m_FirstName
End Get
Set(ByVal value As String)
m_FirstName = value
End Set
End Property
Public Property LastName() As String
Get
Return m_LastName
End Get
Set(ByVal value As String)
m_FirstName = value
End Set
End Property
Public Property State() As String
Get
Return m_State
End Get
Set(value As String)
m_State = value
End Set
End Property
Public Property City() As String
Get
Return m_City
End Get
Set(value As String)
m_City = value
End Set
End Property
End Class
Imports System.Data.SqlClient
Public Class VendorDB
Public Shared Function GetVendors() As List(Of Vendor)
Dim vendorList As New List(Of Vendor)
Dim connection As SqlConnection = PayablesDB.GetConnection
Dim selectStatement As String =
"SELECT VendorName, FirstName, Last Name, State, City " &
"FROM Vendor " &
"ORDER BY Description"
Dim selectCommand As New SqlCommand(selectStatement, connection)
Try
connection.Open()
Dim reader As SqlDataReader = selectCommand.ExecuteReader()
Dim vendor As Vendor
Do While reader.Read
vendor = New Vendor
vendor.VendorName = (reader("VendorName")).ToString
vendor.FirstName = reader("Firstname").ToString
vendor.LastName = (reader("LastName")).ToString
vendor.State = (reader("State")).ToString
vendor.City = (reader("City")).ToString
vendorList.Add(vendor)
Loop
reader.Close()
Catch ex As SqlException
Throw ex
Finally
connection.Close()
End Try
Return vendorList
End Function
End Class
Public Class GLAccount
Private m_Description As String
Public Sub New()
End Sub
Public Property Description() As String
Get
Return m_Description
End Get
Set(ByVal value As String)
m_Description = value
End Set
End Property
Imports System.Data.SqlClient
Public Class GLAccountDB
Public Shared Function GetGLAccountList() As List(Of GLAccount)
Dim accountList As New List(Of GLAccount)
Dim connection As SqlConnection = PayablesDB.GetConnection
Dim selectStatement As String =
"SELECT Description " &
"FROM GLAccounts " &
"ORDER BY Description"
Dim selectCommand As New SqlCommand(selectStatement, connection)
Try
connection.Open()
Dim reader As SqlDataReader = selectCommand.ExecuteReader()
Dim account As GLAccount
Do While reader.Read
account = New GLAccount
account.Description = reader("Description").ToString
accountList.Add(account)
Loop
reader.Close()
Catch ex As SqlException
Throw ex
Finally
connection.Close()
End Try
Return accountList
End Function
End Class
Now this is what I have referred to the payables(form and validator class)
Public Class Validator
Public Shared Function IsPresent(control As Control) As Boolean
Dim comboBox As ComboBox = CType(control, ComboBox)
If comboBox.SelectedIndex = -1 Then
MessageBox.Show(comboBox.Tag.ToString & " is a required field.")
comboBox.Select()
Return False
Else
Return True
End If
End Function
End Class
Payables
Public Class Form1
Dim vendorList As List(Of Vendor)
Dim accountList As List(Of GLAccount)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LoadComboBoxes()
End Sub
Private Sub LoadComboBoxes()
accountList = GLAccountDB.GetGLAccountList
cboAccounts.DataSource = accountList
cboAccounts.DisplayMember = "Description"
End Sub
Private Sub btnGetVendors_Click(sender As Object, e As EventArgs) Handles btnGetVendors.Click
Dim vendorList As List(Of Vendor)
Try
If Vendor.Count > 0 Then
vendorList = VendorDB.GetVendors()
Else
MessageBox.Show("All invoices were paid in full")
End If
Catch ex As Exception
End Try
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
End Class

How pass more than one values in a Single variable to a Function in vb.net

I am using vb.net
I have a Function in my class(class1) file namely save. This Save function have 3 arguments. Now i am using the following approach to send arguments.
Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
dim p as new class1
p.save(txtempid.text,txtempname.text,txtage.text)
messagebox.show("Successfully Saved")
End sub
Class1:
imports system.data.sqlclient
imports system.configuration
public class class1
Dim constr As String
Dim con As SqlConnection
Dim cmd As SqlCommand
public function save(byval s as string,byval s1 as string,byval s2 as string)
constr = ConfigurationManager.AppSettings("con")
con = New SqlConnection(constr)
con.Open()
cmd=new sqlcommand("Emp_insert",con)
cmd.commandtype=commandtype.storedprocedure
cmd.Parameters.Add("#EmployeeID", SqlDbType.BigInt).Value = s
cmd.Parameters.Add("#EmployeeName", SqlDbType.VarChar).Value = s1
cmd.Parameters.Add("#Age", SqlDbType.BigInt).Value = s2
cmd.executenonquery()
cmd.dispose()
con.close()
return 0
End function
End Class
It's ok, but when i have more numerber of arguments it's hard. can any one suggest me better way?
Modification
public function save(parameters as Dictionary(Of string, object)) as int
for each item as KeyvaluePair(Of string, object) in parameters
cmd.Parameters.AddWithValue("#" & item.Key, item.Value)
next
return cmd.ExecuteNonQuery()
end function
You can use Tuple
public sub DoSomething(Tuple (Of string, string, integer) myparameter)
dim firstItem as string = myparameter.Item1
dim secondItem as string = myparameter.Item2
dim thirdItem as integer = myparameter.Item3
end sub
sub main()
Dim tuple as New Tuple(Of string, string, integer)("First","Second", 100)
DoSomething(tuple)
end sub