简体   繁体   中英

VB.NET Declaration error

I am having some trouble in some Visual Basic code where although I have declared a variable, when I try to give it a value, Visual Studio returns an error saying that the variable hasn't been declared. Here is the block of code:

Private Sub chkbox_ta_CheckedChanged(sender As Object, e As EventArgs) Handles chkbox_ta.CheckedChanged
    Dim query As String = "SELECT * FROM [Hiragana List] WHERE Pronunciation='Ta';"
    Dim instruction As SqlCommand (query, connection)
    Dim da As New SqlDataAdapter
    da.SelectCommand = instruction
    da.Fill(HiraganaList)
End Sub

The error is thrown up by the 'instruction' variable and Visual Studio hasn't provided any solutions. In addition to this, the query argument within the instruction variable returns the error 'Array bounds cannot appear in type specifiers'. I am still getting used to working with SQL in VB and any explanation which would teach me how to avoid these errors would be very helpful.

Wrong syntax in declaration and initialization of the SqlCommand.
The right syntax is one of the following:

Dim instruction As SqlCommand = new SqlCommand(query, connection)

or

Dim instruction As New SqlCommand (query, connection)

or just

Dim instruction = new SqlCommand(query, connection)

The Dim Statement has numerous variations the should be studied carefully (especially in the early days with the language)

Data types (string, integer, date) do not need a "new" declaration. But when you define something that is a class (Like SqlCommand or one you create yourself) it will need to be initialized with "new".

Syntax examples from Steve's earlier post

Dim instruction As SqlCommand = new SqlCommand(query, connection)
Dim instruction As New SqlCommand (query, connection)
Dim instruction = new SqlCommand(query, connection)

Some links that might help out:

http://msdn.microsoft.com/en-us/library/47zceaw7.aspx

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand%28v=vs.110%29.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM