Why does this produce an error

Hammy

Active member
Joined
Jan 15, 2003
Messages
27
Location
Ontario, Canada
I am still tinkering around with ASP.net and have a question with these 2 blocks of code.

This works fine....
PHP:
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.


PHP:
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 shouldnt complain as I got it to work, but I am curious for future reference.

Thanks,
Hammy
 
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.
 
Back
Top