我想在页面加载期间的下拉列表中选择当前月份和年份。 我试过,但是在页面加载时没有在下拉列表中选择该值,这里有什么问题?
到目前为止我已经这样做了:
<asp:DropDownList ID="ddlMonth" runat="server">
<asp:ListItem Text="January" Value="01"></asp:ListItem>
<asp:ListItem Text="February" Value="02"></asp:ListItem>
<asp:ListItem Text="March" Value="03"></asp:ListItem>
<asp:ListItem Text="April" Value="04"></asp:ListItem>
<asp:ListItem Text="May" Value="05"></asp:ListItem>
<asp:ListItem Text="June" Value="06"></asp:ListItem>
<asp:ListItem Text="July" Value="07"></asp:ListItem>
<asp:ListItem Text="August" Value="08"></asp:ListItem>
<asp:ListItem Text="September" Value="09"></asp:ListItem>
<asp:ListItem Text="October" Value="10"></asp:ListItem>
<asp:ListItem Text="November" Value="11"></asp:ListItem>
<asp:ListItem Text="December" Value="12"></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlYear" runat="server">
<asp:ListItem Text="2010" Value="2010"></asp:ListItem>
<asp:ListItem Text="2011" Value="2011"></asp:ListItem>
<asp:ListItem Text="2012" Value="2012"></asp:ListItem>
<asp:ListItem Text="2013" Value="2013"></asp:ListItem>
<asp:ListItem Text="2014" Value="2014"></asp:ListItem>
<asp:ListItem Text="2015" Value="2015"></asp:ListItem>
</asp:DropDownList>
在我的页面加载中:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
'Select Current Month and Year to dropdowns
ddlYear.ClearSelection()
ddlMonth.ClearSelection()
Dim year As String = ddlYear.Items.FindByText(Format(Now, "yyyy")).ToString()
Dim month As String = ddlMonth.Items.FindByText(Today.ToString("MMMM")).ToString()
ddlYear.Items.FindByText(year).Selected = True
ddlMonth.Items.FindByText(month).Selected = True
End If
End Sub
答案 0 :(得分:3)
您需要在下拉列表中设置SelectedValue属性而不是我认为的列表项。
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
'Select Current Month and Year to dropdowns
ddlYear.ClearSelection()
ddlMonth.ClearSelection()
ddlYear.SelectedValue = ddlYear.Items.FindByText(Format(Now, "yyyy")).Value;
ddlMonth.SelectedValue = ddlMonth.Items.FindByText(Today.ToString("MMMM")).Value;
End If
End Sub