【问题标题】:Is there any way to reduce this particular code?有没有办法减少这个特定的代码?
【发布时间】:2016-09-21 09:06:59
【问题描述】:

我想创建一个注册页面,我将在其中提供出生日期作为选项。以下是我用来选择日期的下拉列表代码。我想让它尽可能短。请建议。

<asp:DropDownList ID="days" runat="server" AutoPostBack="True" 
 OnSelectedIndexChanged="days_SelectedIndexChanged" >

   <asp:ListItem>1</asp:ListItem>
   <asp:ListItem>2</asp:ListItem>
   <asp:ListItem>3</asp:ListItem>
   <asp:ListItem>4</asp:ListItem>
   <asp:ListItem>5</asp:ListItem>
   <asp:ListItem>6</asp:ListItem>
   <asp:ListItem>7</asp:ListItem>
   <asp:ListItem>8</asp:ListItem>
   <asp:ListItem>9</asp:ListItem>
   <asp:ListItem>10</asp:ListItem>
   <asp:ListItem>11</asp:ListItem>
   <asp:ListItem>12</asp:ListItem>
   <asp:ListItem>13</asp:ListItem>
   <asp:ListItem>14</asp:ListItem>
   <asp:ListItem>15</asp:ListItem>
   <asp:ListItem>16</asp:ListItem>
   <asp:ListItem>17</asp:ListItem>
   <asp:ListItem>18</asp:ListItem>
   <asp:ListItem>19</asp:ListItem>
   <asp:ListItem>20</asp:ListItem>
   <asp:ListItem>21</asp:ListItem>
   <asp:ListItem>22</asp:ListItem>
   <asp:ListItem>23</asp:ListItem>
   <asp:ListItem>24</asp:ListItem>
   <asp:ListItem>25</asp:ListItem>
   <asp:ListItem>26</asp:ListItem>
   <asp:ListItem>27</asp:ListItem>
   <asp:ListItem>28</asp:ListItem>
   <asp:ListItem>29</asp:ListItem>
   <asp:ListItem>30</asp:ListItem>
   <asp:ListItem>31</asp:ListItem>
</asp:DropDownList>

【问题讨论】:

标签: asp.net .net date


【解决方案1】:

使用下面的代码:

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        BindDays();
    }
}

void BindDays()
{
    for(int i=1; i<=31; i++)
    {
        days.Items.Add(new ListItem(i.ToString()));
    }
}

【讨论】:

    【解决方案2】:

    【讨论】:

    • 如果您可以从链接本身包含一些有用的源代码,那就更好了。如果将来链接断开会发生什么。在这种情况下,您的回答将毫无用处。
    【解决方案3】:

    31 天的下拉菜单最后总是有 31 个选项,如果您不想手动填充,请使用 javascript/jquery 或代码隐藏。

    示例

    对于 javascript:see here

    var min = 1,
        max = 31,
        select = document.getElementById('selectElementId');
    
    for (var i = min; i<=max; i++){
        var opt = document.createElement('option');
        opt.value = i;
        opt.innerHTML = i;
        select.appendChild(opt);
    }
    

    对于 c#:see here 你应该想出这样的东西:

    for (int i = 1; i < 32; i++)
    {
        days.Items.Add(new ListItem(i.ToString(), i.ToString()));
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-17
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 2014-02-25
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      相关资源
      最近更新 更多