检查用户是否通过C#中的CalendarDatePicker输入了日期时间值

时间:2019-01-27 12:43:05

标签: c# datetimepicker

晚上好。我正在开发一个微型程序,该程序需要用户在WPF的“日历日期”选择器中选择日期和时间。然后,用户应单击签入按钮。如果用户没有为入住日期和退房日期选择任何值,我希望禁用“入住”按钮。

主要应用图片: User interface of the application

我的代码: if语句仅包含checkinDate,因为我希望在为checkoutDate编码之前检查代码是否有效。使用ToString()是因为我需要将Calendar Date Picker值转换为字符串,以便其他功能正常工作。我正在使用Visual Studio 2017,它似乎与以前的版本有很大的区别。

        DateTime cid = DateTime.Parse(checkinDate.Date.ToString());
        DateTime cod = DateTime.Parse(checkoutDate.Date.ToString());
        Stay s = new Stay(cid, cod);
        if (checkinDate is null)
        {
            checkInbtn.IsEnabled = false;
        }

该代码不起作用,因为在入住和退房日期不包含任何值时,仍未禁用“入住”按钮。每当单击“签到”按钮时,给出的错误消息是:System.FormatException:'字符串未被识别为有效的DateTime。

我围绕google以及堆栈溢出进行了全面的研究,并使用以下方法进行反复试验,但无济于事。

尝试过的代码:

if (checkinDate.GetValue == null)
if (checkinDate.Value == null)
if (checkinDate.Date == null)
if (checkinDate.Date.ToSting()== null)
if (checkinDate.ToString() == null)
if (checkinDate.SelectedDate == null) // Selected date was underlined. Error message:CalendarDatePicker does not contain a definition of 'SelectedDate'

我还将null设置为其他条件,例如'0'和“”。但无济于事。

研究来源: Date time picker validationsCheck if DatePicker value is nullString was not recognized as a valid DateTime " format dd/MM/yyyy"

完整的代码段供您参考:

private void CheckInbtn_Click(object sender, RoutedEventArgs e)
    {
        List<HotelRoom> list1 = new List<HotelRoom>();
        string name = guest.Text;
        string no = passportNo.Text;
        DateTime cid = DateTime.Parse(checkinDate.Date.ToString());
        DateTime cod = DateTime.Parse(checkoutDate.Date.ToString());
        Stay s = new Stay(cid, cod);
        if (checkinDate is null)
        {
            checkInbtn.IsEnabled = false;
        }
        for (int i = 0; i < guestList.Count; i++)
        {
            if (name != guestList[i].Name || no != guestList[i].PpNumber)
            {
                Membership m = new Membership("Ordinary", 0);
                Guest g = new Guest(name, no, s, m, true);
                guestList.Add(g);
            }
            else
            {
                guestList[i].HotelStay = s;
            }
        }
        if (guest.Text.Trim().Length > 0 && passportNo.Text.Trim().Length > 0)
        {
            foreach (HotelRoom r in selectedRoomList)
            {
                list1.Add(r);
            }
            foreach (HotelRoom hotel in list1)
            {
                hotel.IsAvail = false;
                s.AddRoom(hotel);
                selectedRoomList.Remove(hotel);
            }
            statusTxt.Text = "Check in Successful";
            AvailableRoomListView.ItemsSource = null;
            SelectedRoomListView.ItemsSource = null;
        }
    } 

1 个答案:

答案 0 :(得分:0)

尝试一下:

if(!String.IsNullOrEmpty(dateTimePicker1.Value.ToShortDateString()))

{

//您的逻辑在这里

}