【问题标题】:How to show selected index on top in DropDownList?如何在 DropDownList 顶部显示选定的索引?
【发布时间】:2011-06-10 09:54:33
【问题描述】:

实际上,如果月份的值不是 31,它会显示在顶部,否则我会在选择月份的第一个列表中显示月份,否则它会在顶部显示 jan 如何显示另一个?

代码如下:

后面的代码:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    DropDownList2.Items.Clear();
    for (int i = 1; i <= int.Parse(DropDownList1.SelectedValue); i++)
    {
        DropDownList2.Items.Add(new ListItem("" + i));
    }
}

设计师来源:

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
    <asp:ListItem Value="31">Jan</asp:ListItem>
    <asp:ListItem Value="29">Feb</asp:ListItem>
    <asp:ListItem Value="31">Mar</asp:ListItem>
    <asp:ListItem Value="30">April</asp:ListItem>
    <asp:ListItem Value="31">May</asp:ListItem>
    <asp:ListItem Value="30">June</asp:ListItem>
    <asp:ListItem Value="31">July</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList>

问题是:

如果我选择 March 或 may 或任何值为 31 jan 的项目显示在 to 而在其他情况下显示所选的项目。

【问题讨论】:

  • 非常感谢你帮助我,但我是初学者,所以我不太了解代码,但我真的很感谢帮助我学习 asp.net 的人。
  • 我的属性窗口从 Visual Studio 中分离(意味着不以自动隐藏模式显示)如何使其以自动隐藏模式显示
  • 您确实接受了正确但不是最佳解决方案。当您不能这样做时,您为什么要硬编码月份数字;)使用DateTime.DaysInMonth() 确定当前年份和选定月份索引+ 1 的数字(1 月:1、2 月:2、3 月:3 等)
  • 将属性窗口拖到您想要的一侧,然后选择它会要求您选择的模式之一
  • @abatishchev:你能指导我帮助我理解和学习 asp.net 的书籍或网站吗?如果您知道任何提供日常学习任务的网站,请提出建议。谢谢!!!!!!!!!提前

标签: asp.net drop-down-menu list.selectedvalue


【解决方案1】:

ListItems 的值应该是唯一的。

默认选择的项目是 Jan(值 = 31),因此当您单击具有其他值(29 和 30)的项目时,一切都会正常工作。

当您点击三月、五月、七月(值 = 31)时,将选中一月。

要实现您想要的行为,请使用另一种方法。


最好的解决办法是:

using System.Linq;

int count =  DateTime.DaysInMonth(
     DateTime.Today.Year,
     int.Parse(DropDownList2.SelectedIndex + 1)); // sic!

DropDownList2.Items.AddRange(
    Enumerable.Range(1, count)
        .Select(i => new ListItem(i.ToString()))
        .ToArray());

所以你不需要硬编码任何东西!一切都已经在 .NET FCL 中了。只需从列表中的索引中确定月份的编号即可。

【讨论】:

    【解决方案2】:

    我做了一些研究,这不是一个罕见的问题。在 post-back asp.net 将显示列表中的第一个项目以及所选值。我发现的唯一方法是使所有值都独一无二,例如:

    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
        <asp:ListItem Value="Jan-31">Jan</asp:ListItem>
        <asp:ListItem Value="Feb-29">Feb</asp:ListItem>
        <asp:ListItem Value="Mar-31">Mar</asp:ListItem>
        <asp:ListItem Value="April-30">April</asp:ListItem>
        <asp:ListItem Value="May-31">May</asp:ListItem>
        <asp:ListItem Value="June-30">June</asp:ListItem>
        <asp:ListItem Value="July-31">July</asp:ListItem>
    </asp:DropDownList>
    

    然后在 DropDownList1_SelectedIndexChanged 事件中使用 string.split on '-' 来获取天计数值。

    【讨论】:

    • 我的属性窗口从 Visual Studio 中分离(意味着不以自动隐藏模式显示)如何使其以自动隐藏模式显示
    猜你喜欢
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多