开发者

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

开发者 https://www.devze.com 2023-04-05 12:46 出处:网络
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

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

精彩评论

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

关注公众号