开发者

building drop down select in form: code block not supported in this context

I am trying to do something i thought was straightforward [able to do it in PHP this way] but aspx is complaining... the code should build a drop down menu with the numbers from x to y and i wrote it as:

<asp:DropDownList runat="server" ID='DOBD'><asp:ListItem value=''>---</asp:ListItem>
<% for (int i = 1;i<32;i++) { %>
<asp:ListItem value='<%= i %>'><%= i %></asp:ListItem>
<% } %>
</asp:DropDownList>

i am getting the code block error and not sure what to do. thank you in ad开发者_StackOverflow社区vance for your help!


Add items in the codebehind class. You can access any control using id of the control:

this.DOBD.Items.Add(new ListItem("----"));
for (int i = 1; i < 32; i++)
{
    this.DOBD.Items.Add(new ListItem(i.ToString()));
}

also, you can leave your <asp:ListItem value=''>---</asp:ListItem> but in this case you need to set AppendDataBoundItems to true:

<asp:DropDownList ID="DOBD" runat="server" AppendDataBoundItems="true"></asp:DropDownList>

Also, solution without codebehind class:

<%
    for (int i = 1; i < 32; i++)
    {
        this.DOBD.Items.Add(new ListItem(i.ToString()));
    }
%>
<asp:DropDownList ID="DOBD" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Text="---"></asp:ListItem>
</asp:DropDownList>


As an alternative to Samich's answer, you can use a DataSource to fill the dropdown:

<asp:DropDownList runat="server" ID='DOBD' 
     DataSource='<%# System.Linq.Enumerable.Range(1, 32) %>'>
</asp:DropDownList>

<script runat="server"> 
  protected void Page_Load(object sender, EventArgs e)
  { 
     if(! IsPostback) {
        DOBD.DataBind();
     }
  }
</script>

or a ObjectDataSource

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜