【问题标题】:Property .Value not available for DatePicker?属性 .Value 不适用于 DatePicker?
【发布时间】:2017-10-30 04:14:54
【问题描述】:

这可能是一个初学者的问题,但我想从 WPF 应用程序 C# 中的日期选择器字段中获取日期 (yyyy-mm-dd)。我知道我必须使用 DateTime 方法保存日期,因为我要将它插入到数据库中。

我在互联网上看到的每个地方都说使用 .Value 属性,但如果我在 DatePicker 之后键入 .Value 属性,它不会重新调整该属性。

有人知道如何解决此问题或有其他方法从日期选择器中获取日期吗?

private void btnPlanGP_Click(object sender, RoutedEventArgs e)
    {
        try
        {

            string grandPrixNaam = naamGPTextBox.Text;
            DateTime datumGP = new DateTime();
            datumGP = datumDatePicker.Value;
            int aantalRondes = Convert.ToInt32(aantalRondesTextBox.Text);
            string naamBaan = naamBaanComboBox.SelectedItem.ToString();
            int coureurID = Convert.ToInt32(coureurIDComboBox.SelectedItem);
            int gastID = Convert.ToInt32(gastIDComboBox.SelectedItem);

            try
            {
                formule1DataSetGrandPrixTableAdapter.Insert(grandPrixNaam, datumGP, naamBaan, aantalRondes, coureurID, gastID);
                formule1DataSetGrandPrixTableAdapter.Fill(formule1DataSet.GrandPrix);
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(Convert.ToString(ex));
        }
    }

【问题讨论】:

  • 显示你的代码。
  • 在 WPF 中,它被称为 SelectedDate,而不是 Value。 Windows 窗体控件称为DateTimePicker,并具有Value 属性。

标签: c# wpf date datepicker


【解决方案1】:

WPF 中的内置DatePicker 控件有一个SelectedDate,它返回一个DateTime?。试试这个:

string grandPrixNaam = naamGPTextBox.Text;
DateTime datumGP = datumDatePicker.SelectedDate.HasValue ? datumDatePicker.SelectedDate.Value : default(DateTime);
int aantalRondes = Convert.ToInt32(aantalRondesTextBox.Text);
...

【讨论】:

    【解决方案2】:

    我从 Ed Plunkett 那里得到了答复。 WPF 确实没有 .Value 属性。我将其更改为 .SelectedDate 并且有效。

    DateTime? datumGP = new DateTime();
    datumGP = datumDatePicker.SelectedDate;
    

    【讨论】:

    • 你想让我删除我的答案吗?
    • @mm8 你可以把它放在那里。也许有人会更喜欢你的答案。
    • 那你为什么还要写一篇呢?
    • 因为它更短
    • 信息量少了很多。为什么要创建一个新的 DateTime()?没有意义。顺便说一句,我的答案中的附加代码行来自您的代码。我真的不明白为什么您基本上会从试图帮助您的人那里复制答案。但也许这只是我......
    猜你喜欢
    • 2022-10-24
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 2014-01-09
    • 2021-06-03
    • 2012-10-17
    • 1970-01-01
    相关资源
    最近更新 更多