Ryan
Ryan

Reputation: 1791

Variable does not exist in the current context

I'm new to C# .NET. I would like to ask how this works... What I want is just to show an age selection from 1 to 100.

Inside the .aspx file I put this code, I used data binding for the variable listAge.

<asp:DropDownList ID="AgeDropDown" runat="server">
     <%# listAge %>
</asp:DropDownList>

Here's the code-behind for it:

protected void Page_Load(object sender, EventArgs e)
{            
    for (int i = 1; i < 101; i++)
    {
        string listAge;
        listAge = "<asp:ListItem>"+ i +"</asp:ListItem>";
    }
}

The error shown inside the .aspx is:

Error Creating Control: AgeDropDown - Code blocks are not supported in this context.

Because of the variable listAge?

Thank you for the help!

Upvotes: 0

Views: 2048

Answers (3)

Pasman
Pasman

Reputation: 445

Drop the <% %> section in .aspx and in code behind you should do something like this:

protected void Page_Load(object sender, EventArgs e)
{         
    AgeDropDown.Items.Clear();   
    for (int i = 1; i < 101; i++)
    {
        AgeDropDown.Items.Add(new ListItem(i.ToString(),i.ToString()));
    }
}

From another point of view there are several flaws in your code:

  1. You are generating ASP.NET tags in code behind. ASP tags are processed on the server and are rendered into html tags. You were practically inserting a tag in html, which browsers will render as simple text since it's not a valid HTML tag.
  2. You were creating a new listAge variable on each iteration of the for loop. Even if the code would work it would display just the last item

Upvotes: 2

Ken D
Ken D

Reputation: 5968

You could use the server version of AgeDropDown.

ListItem li;
for (int i = 1; i < 101; i++)
{
    li = new ListItem(i.ToString(), i.ToString());
    AgeDropDown.Items.Add(li);
}

Upvotes: 1

Kaido
Kaido

Reputation: 4001

Is this in asp.net or MVC?

Probably

... <%# listAge %>

should be

... <%= listAge %>

Upvotes: 0

Related Questions