Set var foreach for later use

I am trying to set a value in foreach, but I am getting the error it has in the current contect.

Here is my code;

    @{
        string sUsr = System.Web.HttpContext.Current.Request.ServerVariables["AUTH_USER"].ToLower();
        var db = Database.Open("SQLServerConnectionString");
        var selectUser = "SELECT * FROM USERS WHERE username = " + @sUsr;

        }
    @foreach (var userid in db.Query(selectUser)) 
                            {
                                var sReg = userid.userdisplayname;
                                var sAns = userid.usersign;
                                var smail = userid.usermail;
                            }
 ...some html code etc.

    @sReg   <---- The name sReg dosent exist in the current context

      

If I try to use the following code it works and Hello World is displayed on my web page.

    @{ var myMessage =  "Hello World"; }

 ...some html code etc.

    @myMessage

      

+3


source to share


2 answers


Modify your code so that sReg is defined outside the scope of the foreach loop. You can do it like this:

var sReg;
@foreach (var userid in db.Query(selectUser)) 
{
    sReg = userid.userdisplayname;
    var sAns = userid.usersign;
    var smail = userid.usermail;
}

      

Now you can use the (last) sReg value outside of the loop body.



Variables defined in code have a limited scope in which they are available, which is commonly referred to as the "scope" of the variable.
Read this article to learn more about scope in C #.

Also remember that you can get multiple results for your query (unless you choose the first or one). In this case, your sReg variable will only contain the value of the last iteration, which may not be desirable for you. In this case, the list can come to the rescue: http://www.dotnetperls.com/list

+1


source


sReg

in this context only applies in your loop foreach

.

The reason you are getting does not exist in the current context error because it is out of scope.



If you want to go ahead and do something with var sReg

yours, you will need to perform whatever operation you would like to do in the loop, or declare it externally if necessary.

Hope it helps

+1


source







All Articles