5

如何将以下代码中的's 设置为当月DefaultValue的开始日期(第一个 ControlParameter)和最后一个日期(第二个 ControlParameter) ?

<SelectParameters>
    <asp:ControlParameter ControlID="txtFromDate" Name="ExpenseDate" PropertyName="Text"
         Type="String" DefaultValue="01-05-2013" ConvertEmptyStringToNull="true" />
    <asp:ControlParameter ControlID="txtToDate" Name="ExpenseDate2" PropertyName="Text" 
         Type="String" DefaultValue="30-05-2013" ConvertEmptyStringToNull="true" />
</SelectParameters>
4

4 回答 4

16
DateTime today = DateTime.Today;
int daysInMonth = DateTime.DaysInMonth(today.Year, today.Month);

DateTime startOfMonth = new DateTime(today.Year, today.Month, 1);    
DateTime endOfMonth = new DateTime(today.Year, today.Month, daysInMonth);

然后您可以将这些值设置为您的控件。

于 2013-05-14T18:53:12.533 回答
4
DateTime now = DateTime.Now;
this.txtFromDate.Text = New DateTime(now.Year, now.Month, 1).ToString("dd-MM-yyyy");

DateTime lastDayOfMonth = now.AddMonths(1).AddDays(-1);
this.txtToDate.Text = lastDayOfMonth.ToString("dd-MM-yyyy");

我是凭记忆做的。抱歉有任何错误或拼写错误,但差不多就是这样。

于 2013-05-14T18:52:10.490 回答
0

如果您的示例中日期时间的格式是正确的,那么这应该有效:

<asp:ControlParameter ControlID="txtFromDate" 
                      Name="ExpenseDate" 
                      PropertyName="Text" 
                      Type="String" 
                      DefaultValue="<%= string.Format(CultureInfo.InvariantCulture, "01-{0:MM-yyyy}", DateTime.Today) %>" 
                      ConvertEmptyStringToNull="true" />
<asp:ControlParameter ControlID="txtToDate" 
                      Name="ExpenseDate2" 
                      PropertyName="Text" 
                      Type="String" 
                      DefaultValue="<%= string.Format(CultureInfo.InvariantCulture, "{0}-{1:MM-yyyy}", DateTime.DaysInMonth(DateTime.Today.Year, DateTime.Today.Month), DateTime.Today) >" 
                      ConvertEmptyStringToNull="true" />
于 2013-05-14T19:01:03.330 回答
0

我给自己写了一些扩展方法来处理这些场景:

public static class DateTimeExtensionMethods
{
        /// <summary>
        /// Returns the first day of the month for the given date.
        /// </summary>
        /// <param name="self">"this" date</param>
        /// <returns>DateTime representing the first day of the month</returns>
        public static DateTime FirstDayOfMonth(this DateTime self)
        {
            return new DateTime(self.Year, self.Month, 1, self.Hour, self.Minute, self.Second, self.Millisecond);
        }   // eo FirstDayOfMonth


        /// <summary>
        /// Returns the last day of the month for the given date.
        /// </summary>
        /// <param name="self">"this" date</param>
        /// <returns>DateTime representing the last of the month</returns>
        public static DateTime LastDayOfMonth(this DateTime self)
        {
            return FirstDayOfMonth(self.AddMonths(1)).AddDays(-1);
        }   // eo LastDayOfMonth
}
于 2013-05-14T19:03:12.090 回答