如何在DataTable中填写所选月份的所有日期

时间:2015-03-24 04:47:10

标签: c# date

我正在尝试在DataTable中填写所选月份的所有日期。我做了类似下面提到的方法,但它没有工作。

public DataTable  GetDates()
{
DataTable dt = new DataTable();
int year = Convert.ToInt32(ddyear.SelectedItem.Value);//I selected year 2015
int month = Convert.ToInt32(ddmonth.SelectedItem.Value);//I selected  month 3
for ( date = new DateTime(year, month, 1); date.Month == month; date =    date.AddDays(1))
{
  dt.Rows.Add(date);
  date = date.AddDays(1);
}
return dt;
}

我该怎么做?

1 个答案:

答案 0 :(得分:0)

    public DataTable GetDates()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Date", typeof(DateTime));

        int year = Convert.ToInt32(ddyear.SelectedItem.Value);
        int month = Convert.ToInt32(ddmonth.SelectedItem.Value);

        int daysInMonth = DateTime.DaysInMonth(year, month);
        for (int i = 0; i < daysInMonth; i++)
        {
            DataRow dr = dt.NewRow();
            dr["Date"] = new DateTime(year, month, i + 1);
            dt.Rows.Add(dr);
        }

        return dt;
    }