I wonder if is possible to add DropDown item in the Page instead of Code-behind?
So say I have a DropDown box I want to show year 1900 ~ current year
<asp:DropDownList ID="ddlYear" runat="server" CssClass="text">
<%
int currentYear = DateTime.Now.Year;
for (int i = 1900; i < currentYear; i++)
{
%>
<asp:ListItem><%=i %></asp:ListItem>
<%
}
%>
</asp:DropDownList>
Is it possible to do something like that?
Because when I try to do like above it gives me:
Warning 1 C:\SandBox\MyWebApplication1\MyWebApplication1\Default.aspx:
ASP.NET runtime error: Code blocks are not supported in this
context. C:\SandBox\MyWebApplication1\MyWebApplication1\Default.aspx 35 1 MyWebApplication1
Edit: I also tried:
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<%
int currentYear = DateTime.Now.Year;
if (currentYear <= 1933)
{
currentYear = 2012;
}
for (int i = 1933; i < currentYear; i++)
{
DropDownList1.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
%>
But the DropDownList doesn’t have items when display…
=====
Edit: As Splash-X suggested, now it rendered, but all items gone after postback….
<form id="form1" runat="server">
<div>
<%
int currentYear = DateTime.Now.Year;
if (!Page.IsPostBack)
{
if (currentYear <= 1933)
{
currentYear = 2012;
}
DropDownList1.Items.Clear();
for (int i = 1933; i < currentYear; i++)
{
DropDownList1.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
}
%>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<input id="Button1" type="button" value="button" onclick="MyFunction();"/>
<div id="MyDiv">
</div>
<asp:Button ID="Button2" runat="server" Text="Button" />
</div>
</form>
I had an instance where we had a project written in ASP.NET 2.0 and we no longer had the source code to make changes. We needed to modify the states that were being displayed in a dropdown. The old code had US States and Canadian Provinces and we needed to display States only. The dropdown was bound to data source in the code behind so we clear the items and then add all of the items.
The difference is I’m doing my modifications BEFORE the control and the reason I had to do this is any script that comes after the control is changing the dropdown after it is rendered out to the page.
Try moving your code above the dropdown list. Our code checks to see if there was a post back so we could preserve any value that was previously entered. There is no point reloading the list on every page load, just the first.