Slint
Slint

Reputation: 355

Set var in foreach to use later

I'm trying to set a value in a foreach but i get the error that it dosent exist 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 with the folowing code it works and Hello World is rendered in my webpage

    @{ var myMessage =  "Hello World"; }

 ...some html code etc.

    @myMessage

Upvotes: 3

Views: 856

Answers (2)

Peter Brennan
Peter Brennan

Reputation: 1376

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

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

You can now use the (last) value of sReg outside the loop's body.

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

Please be also aware of the fact that you may get multiple results from your query (unless you are selecting with top 1 or such). In that case, your sReg variable would only contain the value of the last iteration, which may not be desirable for you. In this case, a List could come to the rescue: http://www.dotnetperls.com/list

Upvotes: 1

Harry Sweetman
Harry Sweetman

Reputation: 61

sReg in this context only applied inside your foreach loop.

The reason you're getting the doesn't exist in current context error is because it's not in scope.

If you wanted to proceed and do something with your var sReg you would have to perform whatever operation you would like to do within the loop, or declare it outside if need be.

Hope this helps

Upvotes: 1

Related Questions