ASP.NET如何有效地在下拉列表中添加整数

时间:2016-03-01 15:33:48

标签: c# asp.net

我正在为婚姻网站制作个人资料页面。我在make profile页面中使用这些函数。有没有办法优化这些函数?它们在ASP.NET页面的页面加载事件中不是IsPostBack条件下调用,并且迭代次数过多。

private void LoadTime()
    {
        string text = string.Empty;
        //hour
        for (int i = 0; i < 12; i++)
        {
            text = (i + 1 < 10) ? "0" + (i + 1).ToString() : (i + 1).ToString();
            ListItem li = new ListItem(text, i.ToString());
            ddlHour.Items.Add(li);
        }
        //min
        for (int i = 0; i < 60; i++)
        {
            text = (i < 10) ? "0" + i.ToString() : i.ToString();
            ListItem li = new ListItem(text, i.ToString());
            ddlMin.Items.Add(li);
        }
    }

    private int loadfromage()
    {
        int from = (rbtnMale.Checked && !rbtnFemale.Checked) ? 18 : 21;
        //from age
        for (int i = from; i <= 49; i++)
        {
            string text = i.ToString();
            ListItem li = new ListItem(text, i.ToString());
            ddlFromAge.Items.Add(li);
        }
        return from;
    }

    private void loadtoage(int fromage)
    {
        //to age
        for (int i = fromage; i <= 50; i++)
        {
            string text = i.ToString();
            ListItem li = new ListItem(text, i.ToString());
            ddlToAge.Items.Add(li);
        }
    }

    private void loadfromheight()
    {
        //from height
        for (int i = 4; i <= 7; i++)
        {
            string text = i.ToString();
            ListItem li = new ListItem(text, i.ToString());
            ddlppFromHeightFeet.Items.Add(li);
        }
        for (int i = 0; i <= 11; i++)
        {
            string text = i.ToString();
            ListItem li = new ListItem(text, i.ToString());
            ddlppFromHeightInches.Items.Add(li);
        }

    }

    private int feetToInches(int feet, int inches)
    {
        return (feet * 12) + inches;
    }


    private void loadtoheight(int inches)
    {
        int feet = inches / 12;
        inches %= 12;
        //to height
        for (int i = feet; i <= 8; i++)
        {
            string text = i.ToString();
            ListItem li = new ListItem(text, i.ToString());
            ddlppToHeightFeet.Items.Add(li);
        }
        for (int i = inches; i <= 11; i++)
        {
            string text = i.ToString();
            ListItem li = new ListItem(text, i.ToString());
            ddlppToHeightInches.Items.Add(li);
        }

    }

1 个答案:

答案 0 :(得分:0)

  private void loadtoage(int fromage)
{
    //to age
    for (int i = fromage; i <= 50; i++)
    {
        string text = i.ToString();// convert i to string just once. you are converting it again in next line. boxing and unboxing is expensive when it comes to performance. 
        ListItem li = new ListItem(text, i.ToString());//Rather than doing i.ToString() again, you can directly pass text. Its all same. 
        ddlToAge.Items.Add(li);
    }
}

我看到你有很多地方在做这件事。