Hammy Posted March 2, 2003 Posted March 2, 2003 I am still tinkering around with ASP.net and have a question with these 2 blocks of code. This works fine.... 'set up connection string dim objConn as String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=C:\inetpub\wwwroot\tyaspnet21days\bank\banking.mdb" 'set up the SQL command string dim strSQL as String If Not Request.QueryString("UserID") Is Nothing strSQL = "SELECT * FROM tblUsers WHERE UserID = " & Request.QueryString("UserID") Else strSQL = "SELECT * FROM tblUsers" End If 'open the connection dim objCmd as new OleDbDataAdapter(strSQL, objConn) 'fill dataset dim ds as DataSet = new DataSet() objCmd.Fill(ds, "tblUsers") 'select data view and bind to server control MyDataList.DataSource = ds.Tables("tblUsers").DefaultView MyDataList.DataBind() However, if I change slightly, and declare the strSQL string inside my if blocks, insetad of before them, I get an error. The error says "Compiler Error Message: BC30451: Name 'strSQL' is not declared." but as near as I can figure, it is declared inside the if block. 'set up connection string dim objConn as String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=C:\inetpub\wwwroot\tyaspnet21days\bank\banking.mdb" 'set up the SQL command string If Not Request.QueryString("UserID") Is Nothing dim strSQL as String = "SELECT * FROM tblUsers WHERE UserID = " & Request.QueryString("UserID") Else dim strSQL as String = "SELECT * FROM tblUsers" End If 'open the connection dim objCmd as new OleDbDataAdapter(strSQL, objConn) 'fill dataset dim ds as DataSet = new DataSet() objCmd.Fill(ds, "tblUsers") 'select data view and bind to server control MyDataList.DataSource = ds.Tables("tblUsers").DefaultView MyDataList.DataBind() Why does declaring the variable inside the if block cause this error? I know I probably shouldn't complain as I got it to work, but I am curious for future reference. Thanks, Hammy Quote
*Gurus* Derek Stone Posted March 2, 2003 *Gurus* Posted March 2, 2003 Variables are only in scope in their containing block. In other words, the variable strSQL exists only between the opening If and closing End If. When you try to reference it outside of that block the compiler will throw an error at you, since it no longer exists. Quote Posting Guidelines
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.