Declaration Expected - vb.net

Good day all. Please advise me
Why I got an error message "Declaration Expected" when put the cursor on cmd variable. What Should I do?! .. the code appears below:
Imports System.Data.Sqlclient
Imports System.Configuration
Partial Class _Default
Inherits Page
Private Shared Connectionstr As String ="DataSource=localhost;initialCatalog=Orders;Integrated Security=true"
Dim conn As SqlConnection = New SqlConnection(Connectionstr)
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText="SELECT * FROM dbo.Customers"
End Class

You are attempting to use the variable command outside a Property, Function, or Method. At the very least, try wrapping your command in a method (Sub) which performs the desired action with the data:
Partial Class _Default
Inherits Page
Private Sub DoSomethingWithCustomers()
Dim conn As SqlConnection = New SqlConnection(Connectionstr)
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = "SELECT * FROM dbo.Customers"
conn.Open()
Dim dr = cmd.ExecuteReader()
' Do something with the data returned . . .
' ...
' Now Cleanup:
conn.Close()
cmd.Dispose()
conn.Dispose()
End Sub
The above can be improved by wrapping your data access objects in Using blocks, which handle proper disposal of unmanaged resources for you:
Private Sub DoSomethingBetterWithCustomers()
Dim SQL As String = "SELECT * FROM dbo.Customers"
Using conn As New SqlConnection(Connectionstr)
Using cmd As New SqlCommand(SQL, conn)
conn.Open()
Dim dr = cmd.ExecuteReader()
' Do something with the data returned
' . . .
dr.Close()
End Using ' Using Block takes carre of Disposing SqlCommand
End Using ' Using Block takes care of Closing and Disposing Connection
End Sub
Beyond that, it is difficult to know what, precisely, you are trying to do with your code, so the two examples above are really, really basic and general.

Related

Custom TableAdapter Delete Method Override

I'm attempting to overload the "Delete" method of a TableAdapter (approach). How can I execute an SQL statement from 'here' to handle the delete?
I've got:
Namespace AFL_BackendDataSetTableAdapters
Partial Class Log_entry_unitTableAdapter
Public Overloads Function Delete(ByVal LogEntryID As Integer) As Integer
Dim SQL As String
SQL = "DELETE FROM log_entry_unit WHERE log_entry_unit_id=" & LogEntryID
'?????.Execute SQL
Return 0
End Function
End Class
End Namespace
The overload is working fine, but I don't know how to do the hard part and actually manipulate the data from here. Previously, I've just gone into the Dataset Designer and manually updated the generated methods to work like I want them, but whenever I use the wizard to regenerate the dataset, that (as expected) gets overwritten.
I've previously only ever manipulated Data using the generated methods, and now I'm stuck.
EDIT w/ Final Answer
Based on William's help below here's the final working solution (Note I just had to use OleDb instead of SQL since my Dataset is Access:
Imports System.Data.OleDb
Namespace AFL_BackendDataSetTableAdapters
Partial Class Log_entry_unitTableAdapter
Public Overloads Function Delete(ByVal LogEntryID As Integer) As Integer
Dim queryString As String = "DELETE FROM log_entry_unit WHERE log_entry_unit_id=" & LogEntryID
Dim command As New OleDbCommand(queryString, Connection)
Dim r As Integer
Try
Connection.Open()
r = command.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
r = 0
Finally
Connection.Close()
End Try
Return r
End Function
End Class
End Namespace
I hardcoded a connection string for reference only. This should be in a config file. As an example:
Dim connectionString As String = _
"Data Source=(local);Initial Catalog=YourDatabase;" _
& "Integrated Security=true"
Dim queryString As String = "DELETE FROM log_entry_unit WHERE log_entry_unit_id=" & LogEntryID
' Create and open the connection in a using block. This
' ensures that all resources will be closed and disposed
' when the code exits.
Using connection As New SqlConnection(connectionString)
' Create the Command
Dim command As New SqlCommand(queryString, connection)
' Open the connection in a try/catch block.
Try
connection.Open()
command.ExecuteNonQuery()
Catch ex As Exception
' handle exception here
End Try
End Using
EDIT
I probably should of mentioned you will probably want to fill your adapter again after the delete.

IS it OK to use a class for connecting to my SQL Server database?

I have a public class called dbOPS that has some subs and functions like:
Public Function getSqlReader(ByVal sql As String) As SqlDataReader
Dim cmd As New SqlCommand(sql, getConn)
cmd.CommandTimeout = 360
Dim dr As SqlDataReader = cmd.ExecuteReader(Data.CommandBehavior.CloseConnection)
Return dr
End Function
Public Function getSqlScalar(ByVal sql As String)
Dim cmd As New SqlCommand(sql, getConn)
cmd.CommandTimeout = 360
Dim cnt = cmd.ExecuteScalar
closeCX()
Return cnt
End Function
Public Sub ExecuteSql(ByVal sql As String)
Dim cmd As New SqlCommand(sql, getConn)
cmd.CommandTimeout = 360
cmd.ExecuteNonQuery()
closeCX()
End Sub
I then use the following command once per page and use the db variable many (many) times throughout the page:
Dim db as new dbOPS
Recently, I have started getting many errors
ExecuteScalar requires an open and available connection. the connection's current state is connecting
Is this the cause?
Is there any way around it without rewriting every page and every command to open its own connection?
Thanks
It's probably best to detect the connection and reopen them just in case it is not open prior to executing the command.
If (cmd.Connection.State != ConnectionState.Open) Then
cmd.Connection.Open()
Do this as part of your helper methods.

how to populate items from database in a listbox in vb.net

I was developing an application using oop concept.I have a class that has 2 attributes and have Get and Set methods namely WorkItemNumber and Description.
On the client side i have a list box used to populate the work items based on their description.Here's the code i wrote in the class o read items from the database.
Public Sub LoadWorkItem()
' Load the data.
' Select records.
Dim oWorkItem As WorkItem = New WorkItem()
Dim conn As New OleDbConnection
Dim data_reader As OleDbDataReader
conn = oWorkItem.GetDbConnection()
Dim cmd As New OleDbCommand("SELECT * FROM work_item ORDER BY [work item number]", conn)
data_reader = cmd.ExecuteReader()
'ListBox1.Items.Clear()
If data_reader.HasRows = True Then
Do While data_reader.Read()
WorkItemNumber = data_reader.Item("work item number")
Description = data_reader.Item("description")
Loop
End If
data_reader.Close()
data_reader = Nothing
cmd.Dispose()
cmd = Nothing
conn.Close()
conn.Dispose()
End Sub
How do i populate the listbox using the code,and if there's any improvement on the code please do tell me as well.Thank you
To poulate your ListBox, do this...
ListBox1.Item.Clear()
If data_reader.HasRows Then
Do While data_reader.Read()
WorkItemNumber = data_reader.Item("work item number")
Description = data_reader.Item("description")
ListBox1.Items.Add(New ListItem(Description, WorkItemNumber)
Loop
End If
As far as improvements, start by using a Using statement for the DB connection. In your code, if there is an exception while the database connection is open, it will never get closed. This is better...
Using conn As OleDbConnection = oWorkItem.GetDbConnection()
' Execute SQL and populate list...
End Using
The above code assures that your connection will be closed.
Then, turn on Option Strict and Option Explicit. This will force you to declare the Type for Description and WorkItemNumber and cast them as Strings when adding a ListItem. This will reduce run-time errors.
Finally, if this is anything but a small app you are doing as a learning experiment, you should read up on tiered application design. Your code is mixing UI, business logic, and data access in the same method. This is generally frowned upon.
Your "user interface" LoadWorkItem() method should ask a "core" method for a list of WorkItems.
Your core method should then ask a "data access" method for data.
The "data access" method should make the call to the database.
Happy coding.
Update: You can find excellent info about n-Tier architecture on MSDN. A good book to read once you grasp the fundamentals and have some confidence in .NET is Visual Basic .NET Business Objects.
Imports System.Data.SqlClient 'Reference The Sql Client
Public Class Form1
''Make sure to change the connection string below to your connection string this code only works for SQL DataBase. If Your connection String is wrong This will Not Work
Dim connString As String = "Data
Source=NameofYourSQLServer\SQLEXPRESS;Initial Catalog=NameOfYourDataBase;Integrated Security=True"
Dim tblDIV As DataTable
Dim daDIV As SqlDataAdapter
Dim dsDIV As New DataSet
Dim oCon As SqlConnection
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim oCon = New SqlConnection
oCon.ConnectionString = connString
dsDIV = New DataSet
' Select all Fields and order by ID or Replace * with name of Field
daDIV = New SqlDataAdapter("SELECT * FROM NameOfYourTable ORDER BY Id DESC", oCon)
'*** Define command builder to generate the necessary SQL
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(daDIV)
builder.QuotePrefix = "["
builder.QuoteSuffix = "]"
Try
daDIV.FillSchema(dsDIV, SchemaType.Source, "DIV")
daDIV.Fill(dsDIV, "DIV")
tblDIV = dsDIV.Tables("DIV")
ListBox1.DataSource = tblDIV
ListBox1.DisplayMember = "NameOfTheFieldYouWanttoDisplay"
Catch ex As Exception
MsgBox("Encountered an Error;" & vbNewLine & ex.Message)
oCon.Close()
End Try
End Sub

How to create strongly typed list class in vb.net

I hate to admit this but I am new to object oriented programming in VB.NET. I have a class object called Subscriber.vb which works OK but I'd like to create a "set" or list of these objects. Could someone please help me leverage the following code to create a list of the subscribers so a "consumer" could loop through this list of subscribers? Here is what I have so far:
Public Class Subscriber
Public Sub New(ByVal theSubscriberID As Int32)
Dim sConnDatabase As String = ConfigurationManager.ConnectionStrings("DatabaseConnString").ConnectionString
Dim connection As New SqlConnection(sConnDatabase)
Dim cmd As SqlCommand
Try
cmd = New SqlCommand("GetSubscriberInfo_v", connection)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#SubscriberID", theSubscriberID)
connection.Open()
Dim objReader As SqlDataReader = cmd.ExecuteReader()
Do While objReader.Read()
SetObjectData(objReader)
Loop
objReader.Close()
connection.Close()
Catch ex As Exception
Throw
End Try
End Sub
Private Sub SetObjectData(ByVal theObjReader As SqlDataReader)
Try
Me._ID = Convert.ToInt32(theObjReader("SubscriberID"))
Me._NameForLogon = theObjReader("SubscriberName").ToString()
Me._NameInFull = theObjReader("SubscriberNameFull").ToString()
Me._DaysUntilExpired = Convert.ToInt32(theObjReader("DaysUntilExpired"))
Me._SignupDate = theObjReader("SignupDate")
Me._ExpirationDate = theObjReader("ExpirationDate")
Me._SubscriberPhone = theObjReader("SubscriberPhone").ToString()
Me._MostRecentRenewal = theObjReader("MostRecentRenewal")
Me._CumulativeRevenue = Convert.ToDecimal(theObjReader("CumulativeRevenue"))
Me._NumberOfRenewals = theObjReader("NumberOfRenewals")
Me._SubscriptionStatusCode = theObjReader("SubscriptionStatusCode")
Me._SubscriptionStatus = theObjReader("SubscriptionStatus").ToString()
Me._NotificationStatusCode = theObjReader("NotificationStatusCode")
Me._NotificationStatus = theObjReader("NotificationStatus")
Catch ex As Exception
Throw
End Try
End Sub
End Class
I did not show the getters and setters. This has to be restricted to Visual Studio 2008 unfortunately. For a few reasons, we cannot upgrade this environment.
What would be the best practice here? Add a Public Class SubscriberList to the Subscriber.vb file or should it be a separate file? More importantly, I am stuck on how to take what I have an create a proper list. Then the caller would create an instance of the SubscriberList object. Please help me get started. Thanks.
EDIT: Here is what I came up with thanks to your idea (I'm thinking of adding some overloaded constructors which might filter the data some various ways...would that be a good practice?):
Public Class SubscriberList
Public Sub New()
Dim sConnDatabase As String = ConfigurationManager.ConnectionStrings("DatabaseConnString").ConnectionString
Dim connection As New SqlConnection(sConnDatabase)
Dim cmd As SqlCommand
Dim oSubscriberList As New List(Of Subscriber)
cmd = New SqlCommand("GetSubscriberInfo_v", connection)
cmd.CommandType = CommandType.StoredProcedure
connection.Open()
Dim objReader As SqlDataReader = cmd.ExecuteReader()
Do While objReader.Read()
Dim id As Integer = objReader("SubscriberID")
Dim s As Subscriber = New Subscriber(id)
oSubscriberList.Add(s)
Loop
objReader.Close()
connection.Close()
End Sub
End Class
New error trying to use:
Dim allSubscribers As New SubscriberList
For Each Subscriber In allSubscribers
' allSubscribers is not declared
Next
Why not declared ? Confused rookie mistake I am sure...
EDIT (Number 2):
Changed name from SubscriberList to Subscribers plural & got this working (see below) - but I am very puzzled by the advice to remove the database connection and query from the constructor(s) and place in separate class(es). I was picturing adding overloaded constructors to Subscriber (and Subscribers). I cannot imagine how the constructors of each would get their respective data.
Public Class Subscribers
Implements IEnumerable(Of Subscriber)
#Region "properties"
Public List As New List(Of Subscriber)
#End Region
Public Function GetEnumerator() As IEnumerator(Of Subscriber) _
Implements IEnumerable(Of Subscriber).GetEnumerator
Return List.GetEnumerator()
End Function
Private Function GetEnumerator1() As IEnumerator _
Implements IEnumerable.GetEnumerator
Return List.GetEnumerator()
End Function
Public Sub New()
Dim sConnDatabase As String = ConfigurationManager.ConnectionStrings("DatabaseConnString").ConnectionString
Dim connection As New SqlConnection(sConnDatabase)
Dim cmd As SqlCommand
cmd = New SqlCommand("SELECT * FROM dbo.Subscriber_v", connection)
cmd.CommandType = CommandType.Text
connection.Open()
Dim objReader As SqlDataReader = cmd.ExecuteReader()
Do While objReader.Read()
Dim id As Integer = objReader("SubscriberID")
Dim s As Subscriber = New Subscriber(id)
List.Add(s)
Loop
objReader.Close()
connection.Close()
End Sub
End Class
In VB you can make a list of a custom object.
dim oSubscriberList as new List(of Subscriber)
Then you can instantiate new subscribers and add them to the list
oSubscriberList.add('add object here')
This is probably the most simple, quick and dirty way to handle it. You can also create a separate class to create a collection of your object. "Best" practices, if you want to follow SOLID programming principles and use test driven development, would point you towards making a separate collection class to deal with it, but it isnt necessary.
EDIT: as per comment below
You dont need to create a subscriberlist class. Just create a regular list of Subscribers and add them to the list as so. Do this where you are wanting to create this list (form load, some event, etc.)
Dim oSubscriberList as NEW List(of Subscriber)
Dim sConnDatabase As String = ConfigurationManager.ConnectionStrings("DatabaseConnString").ConnectionString
Dim connection As New SqlConnection(sConnDatabase)
Dim cmd As SqlCommand
cmd = New SqlCommand("SELECT * FROM dbo.Subscriber_v", connection)
cmd.CommandType = CommandType.Text
connection.Open()
Dim objReader As SqlDataReader = cmd.ExecuteReader()
while objReader.Read()
oSubscriberList.Add(New Subscriber(objReader("SubscriberID"))
end while
'additional cleanup steps here
Then you can just iterate over you list as so:
For each sub as Subscriber in oSubscriberList
'do something
Next

VB.NET connection to MS Access

I get an error when I am trying to connect to a Microsoft Access DB using VB.NET. I see examples all over the web. My code looks like those examples, however I am getting a build error message stating:
Type 'System.Data.OleDb.OleDbConnection' is not defined.
I have tried adding some kind of import statement for the system.data.oledb... but that does not seem to work. My code is below. It is a basic connection so I am thinking that I am missing some kind of add in, library, or setting. Any and all help would be greatly appreciated.
Public Function TestMain(ByVal args() As Object) As Object
' Connection String to MS Access DB
Dim connectStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Users\DMalerman\keyword.accdb;" & _
"Persist Security Info=False;"
MsgBox(connectStr)
' Create connection to the db
Using connection As New System.Data.OleDb.OleDbConnection(connectStr)
' Create the SQL Query
Dim readQuery As String = "Select KeywordDriver.ScriptName from KeywordDriver " & _
"where KeywordDriver.Keyword = test"
Dim queryCommand As New System.Data.OleDb.OleDbCommand(readQuery, connection)
'Open the Connection
connection.Open()
' Query the Database
Dim dbReader As System.Data.OleDb.OleDbDataReader = queryCommand.ExecuteReader()
' Loop until there is nothing left to read
While dbReader.Read()
Dim sKeyword As String = ""
sKeyword = dbReader.GetString(0)
MsgBox(sKeyword)
End While
' Close the Reader
dbReader.Close()
End Using
Return Nothing
End Function
did you try
imports System.Data.OleDb
?
if so, did it give you an error?
Please try to modify this line:
Dim queryCommand As New System.Data.OleDb.OleDbCommand(readQuery, connection)
by putting these only:
Dim queryCommand As New System.Data.OleDb.OleDbCommand(readQuery)
queryCommand.Connection = connection
Imports System.Data
Imports System.Data.OleDb
Module Module1
Public str As String
Public con As OleDbConnection
Public cmd As OleDbCommand
Public dtreader As OleDbDataReader
Public dtadapter As OleDbDataAdapter
Public Sub openconn()
str = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database2.mdb"
con = New OleDbConnection(str)
Try
con.Open()
Catch ex As Exception
MessageBox.Show("gagal koneksi")
End Try
End Sub
End Module