Gemma Church
Gemma Church

Reputation: 63

ASP.NET to see if a number is even or odd

I'm using the following code in a loop to find out if a variable is odd or even (only wanting to show the even results here) but I get the following error message "The left-hand side of an assignment must be a variable, property or indexer" for the line:

<% if((leftCount % 2) = true) { %>

Here is the code in full:

<% var leftCount = 1;  %>           
            <% foreach (var i in DevelopmentJobs) { %>
                <% if((leftCount % 2) = true) { %>
                DO SOMETHING
                <% } %>

                <% } %>
           <% leftCount++; %>

Thanks

Upvotes: 0

Views: 4898

Answers (3)

Mark S. Rasmussen
Mark S. Rasmussen

Reputation: 35476

<% if((leftCount % 2) = true) { %>

Should be:

<% if(leftCount % 2 == 0) { %>

Using a single = sign means you want to assign a value. Using double == means you're testing for a value.

Upvotes: 1

Mister Epic
Mister Epic

Reputation: 16723

leftCount % 2 resolves to an integer, not a boolean. You should test its value against the appropriate int value. In this case, if leftCount is divided by two, we are checking that its remainder is equal to zero, which would indicate it is odd or even.

 <% var leftCount = 1;  %>           
        <% foreach (var i in DevelopmentJobs) { %>
            <% if((leftCount % 2 == 0) { %>
            DO SOMETHING
            <% } %>

            <% } %>
       <% leftCount++; %>

ref: http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx

Upvotes: 1

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

Use if((leftCount % 2) == 0. You want to test if the modulo is 0, it's a mathematical expression.

And you need == (comparison) instead of = (assignment)

Upvotes: 3

Related Questions