【问题标题】:C# for loop: Checking if DateTimePicker is weekend or in databaseC# for 循环:检查 DateTimePicker 是周末还是在数据库中
【发布时间】:2021-01-12 23:53:39
【问题描述】:

我不是 IT 专业人士,所以下面的语法是错误的,但它显示了我想要做什么。

我有两个 DateTimePicker:DateTimePicker1 和 DateTimePicker2(DateTimePicker1

  1. 如果是周末。

  2. 如果是数据库表中的日期。

有人可以帮我清理下面的代码吗?

非常感谢!

    public static bool isDateInDatabaseAppointmentTable(DateTime DateTimePicker.Value)  //How to write this statement. Check if the date is in database table
{

    OdbcConnection Cn = new OdbcConnection(GlobalVariables.DatabaseConnectionString);


    string select = "SELECT COUNT(*) from TableAppointment WHERE AppointmentDate = DataTimePicker.Value ";
    //How to write this SQL statement

    using (OdbcCommand cmd = new OdbcCommand(select, Cn))            
    {
        object obj = cmd.ExecuteScalar();

        int count = Convert.ToInt32(obj);

        if (count > 0)
        {
            return true;
        }
        else
        {
            return false;
        }                          

    }


}



for (DateTime dt = DateTimePicker1.Value to DateTimePicker2.Value) 
{
    bool isFound = GlobalMethod.isDateInDatabaseAppointmentTable(dt);

    if (dt == Satursday || dt == Sunday)
    {
    MessageBox.Show("It is weekend, you don't work today")
    //I will do something here, and I think I know how to do it. Just using messagebox to replace it.
    }  
    else if (isFound == true)   
    {
    MessageBox.Show("You have appointment today, and you don't work today")
    //I will do something here, and I think I know how to do it. Just using messagebox to replace it.
    }  
    else
    {
    //I will do something here.
    }


}

【问题讨论】:

  • isDateInDatabaseAppointmentTable 声明声明了一个方法(又名函数)。括号中的内容(您当前拥有的DateTime DateTimePicker.Value)应该是一个参数(例如DateTime theDate)。然后,您可以将其用作方法的局部变量。当您调用该方法时,您会传递一个值(或引用),例如 DateTimePicker.Value,并且该值会在该方法的调用中使用。
  • 我会通过开始和结束日期,并返回这些日期之间的数据库中的所有日期。别忘了,DatePicker.Value 是一个 datetime,所以你想在 SQL cast(@start as date 中将其转换为日期
  • @Flydog57 它只是显示了逻辑(我想做的)。我不是 IT 专业人士,我真的不知道如何正确编写它。语法完全错误。谢谢。

标签: c# visual-studio winforms


【解决方案1】:

要检查这一天是否是周末,首先,您可以参考this answer 以获取两个日期之间所有日期的列表。然后使用where clause 过滤列表以获取所有周末。

DateTime start = dateTimePicker1.Value;
DateTime end = dateTimePicker2.Value;

List<DateTime> weekends = Enumerable.Range(0, 1 + end.Subtract(start).Days)
                        .Select(offset => start.AddDays(offset))
                        .Where(d => d.DayOfWeek == DayOfWeek.Saturday || d.DayOfWeek == DayOfWeek.Sunday)
                        .ToList();

定义方法时,只需要声明其形参即可。至于“DateTimePicker.Value”,作为调用方法时的实参。

// Just define the method like this, use a formal parameter "dt"
public static bool isDateInDatabaseAppointmentTable(DateTime dt)

如果数据库中字段日期的类型为date,则需要将dateTimePicker.Value转换为Date

另外,为了防止sql注入,使用参数是更好的选择。

public static bool isDateInDatabaseAppointmentTable(DateTime dt)
{
    string connSQL = @"connection string";
    using (SqlConnection conn = new SqlConnection(connSQL))
    {
        string strSQL = "select count(*) from TableAppointment WHERE AppointmentDate = CAST(@date AS DATE)";
        SqlCommand cmd = new SqlCommand(strSQL, conn);
        cmd.Parameters.AddWithValue("@date", dt.ToShortDateString());
        conn.Open();
        int rows = (int)cmd.ExecuteScalar();
        if (rows > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

【讨论】:

  • 您好,您之前是来自 social.msdn.microsoft.com 的 Kyle 吗?谢谢你再次帮助我。查询表达式“AppointmentDate = CAST(@date AS DATE)”中的语法错误(缺少运算符)。
  • @VAer 您使用的是什么类型的数据库?尝试将字段名称括在单字节方括号 ([ ]) 中,例如 [AppointmentDate]。这是一个类似的thread
【解决方案2】:

有人可以帮我清理下面的代码吗?

初学者程序员犯的第一个错误是他们试图在一个类和一个过程中做太多事情。

创建每个只做一件事的较小程序,增强您的代码:

  • 更易于阅读和理解它的作用,
  • 在类似情况下更容易重复使用
  • 更容易测试
  • 更易于实施小改动,无需更改所有其他程序。

您需要一个程序来检查 DateTime 是否在周末,或者更准确地说:您想要检查日期是否是非工作日

bool IsNonWorkingDay(DateTime date)
{
    return date.DayOfWeek == DayOfWeek.Saturday
        || date.DayOfWeek == DayOfWeek.Sunday;
}

显然你已经有一个方法来检查日期是否在数据库中:

bool IsInDataBase(DateTime date)
{
    return GlobalMethod.isDateInDatabaseAppointmentTable(date);
}

当然,您不想将自己限制在 DateTimePickers 上。如果在不久的将来希望您创建一个文本框,操作员可以在其中键入日期。

// Checks whether the date is in the database an not a Weekend.
// shows problems to the operator
bool CheckValidDate(DateTime date)
{
    const string errorNonWorkingDayMessage = ...
    const string errorNotInDatabaseMessage = ...
    const string errorCaption = "Problem with Date!";

    if (IsNonWorkingDay(date))
    {
        MessageBox.Show(errorNonWorkingDayMessage, errorCaption, MessageBoxIcon.Warning);
        return false;
    }
    if (!IsInDataBase(date))
    {
        MessageBox.Show(errorNotInDatabaseMessage, errorCaption, MessageBoxIcon.Warning);
        return false;
    }
    return true;       
}

我不确定你什么时候会检查这个。假设您有两个按钮:SelectStartDateButton 和 SelectEndDateButton。如果操作员按下这些按钮之一,则要求操作员选择日期。 DateTimePicker 的标题栏说是哪个日期,初始值为 Today 为起始日期

private DateTime acceptedStartDate;
private DateTime acceptedEndDate;

// Asks the operator to select a date. Returns this date or null if no date is selected
public DateTime? SelectDate(string caption, DateTime initialValue)
{
    using (var dateTimePicker = new DateTimePicker)
    {
        dateTimePicker.Text = caption;
        dateTimePicker.Value = initialValue;
        // consider to set MinDate, MaxDate and others

        // show the DateTimePicker and evaluate the result
        var dlgResult = dateTimePicker.ShowDialog(this);

        if (dlgResult == DialogResult.Ok)
            return dateTimePicker.Value;
        else
            return null;
    }
}

按下按钮选择开始日期/选择结束日期时的事件处理程序:

private void SelectDateButton_Clicked(object sender, ...)
{
    if (Object.ReferenceEquals(sender, this.buttonSelectStartDate)
        this.SelectStartDate();
    else
        this.SelectEndDate();
}

void SelectStartDate()
{
    const string caption = "Select the Start Date";
    bool startDateChanged = this.SelectDate(caption, ref this.acceptedStartDate);
    if (startDateChanged)
    {
         // TODO: process changed start date
    }
}

void SelectEndDate()
{
    const string caption = "Select the End Date";
    bool endDateChanged = this.SelectDate(caption, ref this.acceptedEndDate);
    if (endDateChanged)
    {
         // TODO: process changed end date
    }
}

以下方法要求操作员选择一个日期,使用正确的标题和初始值日期

// if Ok, then date is changed. return value true if changed
bool SelectDate(string caption, ref DateTime date)
{     
    bool dateChanged = false;
    DateTime? selectedDate = this.SelectDate(caption, date);
    if (selectedDate.HasValue)
    {
        DateTime proposedDate = selectedDate.Value;
        if (this.CheckValidDate(proposedDate)
        && date != proposedDate)
        {
            date = proposedDate;
            dateChanged = true;
        }
    }
    return dateChanged;
}

结论

我做了很多小程序:

  • 用于检查任何日期是否为周末日期,
  • 检查数据库中是否有日期
  • 检查日期的有效性,并显示正确的警告消息
  • 要求操作员选择日期
  • 将这一切放在一起:向操作员询问日期、检查有效性并更新日期
  • 处理按钮单击以调用“put-it-all-together”方法的方法。

因为这些方法很小,所以它们易于理解、易于重用和易于测试。

例如:IsNonWorkingDay 可以很容易地用于测试任何日期是否是 NonWorkingDay。无需用户界面即可轻松对该功能进行单元测试。如果你想改变它,使圣诞节也是非工作日,那么只有一种方法需要改变。

而且调用方法很容易更改,无需大量代码更改。例如,如果您不想对按钮单击做出反应,而是在选择开始日期后立即开始选择结束日期:在一个地方只有一个小改动。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多