0

我想在页面加载期间在下拉列表中选择当前的月份和年份。我试过了,但是页面加载时没有在下拉列表中选择该值,这是什么问题?

到目前为止,我已经这样做了:

 <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
4

1 回答 1

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
于 2012-07-31T12:25:51.583 回答