DateTimePicker.MinDate问题

时间:2018-08-02 17:49:31

标签: c# sqlite datetime

我想在DateTimePicker中的VS2015上设置最小和最大日期。我想将最小日期设置为数据库中的值,将最大日期设置为DateTime.Now。我有以下代码:

SQLiteCommand cmdForShopRegDate = new SQLiteCommand(@"select Date from [ShopRegistration]", con);
SQLiteDataAdapter AdapterShopRegDate = new SQLiteDataAdapter(cmdForShopRegDate);
DataTable TableShopRegDate = new DataTable();
AdapterShopRegDate.Fill(TableShopRegDate);
this.dateTimePickerStartReport.MaxDate = System.DateTime.Now.Date;
this.dateTimePickerStartReport.MinDate = Convert.ToDateTime(TableShopRegDate.Rows[0][0].ToString());

我遇到以下错误:

  

值'18 -Jul-28 12:00:00 AM'对于'MinDate'无效。 “ MinDate”必须小于MaxDate。

1 个答案:

答案 0 :(得分:0)

您的问题不是很详细,似乎您是在要求别人为您执行工作。即使这可能是一种学习经验,请仔细阅读how to ask的详细问题。

您遇到的问题与数据格式有关。您正在解析18-Jul-28的值。问题在于,它解析为7/18/2028,肯定大于8/2/2018。要解决此问题,您需要使用以下格式进行解析:

yy-MMM-dd

除此之外,还可以简化代码(除非您绝对需要DataTable)。 SqlLiteCommand.ExecuteScalar返回结果集中第一行的第一列,并忽略所有其他数据。

using (SqlLiteConnection conn = new SqlLiteConnection("put your connection string here")) {
    using (SqlLiteCommand cmd = new SqlLiteCommand("select Date from [ShopRegistration]", conn) {
        conn.Open();
        dateTimePicker.MinDate = DateTime.ParseExact((string)cmd.ExecuteScalar(),
                                                     "yy-MMM-dd",
                                                     CultureInfo.InvariantCulture).Date;
    }
}

dateTimePicker.MaxDate = DateTime.Now.Date;

您需要将using System.Globalization;添加到您的使用中,才能访问CultureInfo

参考