如何在下拉列表中默认显示当前日期?

时间:2013-04-08 03:47:42

标签: c# datetime drop-down-menu

我想在下拉列表中显示一周的日期,默认为今天的日期。我怎样才能做到这一点?

我还被告知“使用类DateTime.Now,并将数据值转换为字符串”。

感谢任何帮助!

3 个答案:

答案 0 :(得分:4)

这适用于我的asp.net项目

DropDownList1.Items.Add(DateTime.Now.ToString());

这个在我的组合框上

comboBox1.Items.Add(DateTime.Now);

我不完全确定你的问题。你想做什么?

for (int i = 0; i < 7; i++)
{
    DropDownList1.Items.Add(DateTime.Now.AddDays(-i).ToString());
}

答案 1 :(得分:2)

试试这个:

 //Get Start And End
            int delta = Convert.ToInt32(DateTime.Now.DayOfWeek);
            delta = delta == 0 ? delta + 7 : delta;
            DateTime moday = DateTime.Now.AddDays(1 - delta);
            DateTime sunday = DateTime.Now.AddDays(7 - delta);
            //Get Date Range
            List<DateTime> allDates = new List<DateTime>();
            //Add To Your List
            for (DateTime i = moday; i <= sunday; i = i.AddDays(1))
            {
                DropDownList1.Items.Add(i.Date.DayOfWeek);
            }
            //Select Today Name
            DropDownList1.SelectedItem = DateTime.Today.Date.DayOfWeek;

<强>被修改

格式(mm/dd/yyy)

//Add To Your List
            for (DateTime i = moday; i <= sunday; i = i.AddDays(1))
            {
                comboBox1.Items.Add(i.Date.ToShortDateString());
            }
            //Select Today Date(dd/mm/yyy)
            comboBox1.SelectedItem = DateTime.Today.ToShortDateString();

答案 2 :(得分:1)

你可以把它放在加载事件

    protected void Page_Load(object sender, EventArgs e)
    {
        for (int i = 0; i < 7; i++)
        {
            DropDownList1.Items.Add(DateTime.Now.AddDays(-i).ToString());
        }


    }