【问题标题】:DateTimePicker not selected in wpf在 wpf 中未选择 DateTimePicker
【发布时间】:2012-05-16 19:26:18
【问题描述】:

我有一个 dateTime 的数据库字段,我在窗口中添加了一个 DateTimePicker 控件,如果没有选择任何日期,我想要它。没有在数据库中输入任何内容我尝试了以下代码并返回错误,有人知道吗? 我正在研究 WPF、C# 和 Access DB

try
{
    string insert_query = "INSERT INTO dbo_tasks ( Date_Created, write_From, Task_To ) " +
                          "VALUES ('" + DP_date.SelectedDate + "', " + txt_from.SelectedValue + ", " + txt_to.SelectedValue + ")";

    con1.Open();
    OleDbCommand cmd = new OleDbCommand(insert_query, con1);
    cmd.ExecuteNonQuery();
}
catch (Exception)
{

    MessageBox.Show("");
}
con1.Close();

【问题讨论】:

  • catch (Exception) 更改为catch (Exception e)MessageBox.Show(""); 更改为MessageBox.Show(e.Message);。这样你就会看到错误。
  • Date_Created 是数据库中可以为空的日期时间字段吗?
  • 是的,如果我这样写字符串 insert_query = "INSERT INTO dbo_tasks (Date_Created, write_From, Task_To) VALUES ('" + null+ "', " + txt_from.SelectedValue + ", " + txt_to.选定值 + ")";它有效
  • 正如@juergen d 所暗示的那样,如果您发现实际的错误消息是什么,那将非常有用......

标签: .net wpf ms-access


【解决方案1】:

如果没有选择日期,您需要添加逻辑。

"INSERT INTO dbo_tasks (Date_Created, write_From, Task_To) VALUES ('" + null+ "', " + txt_from.SelectedValue + ", " + txt_to.SelectedValue + ")"

问题是如果没有选择日期,DP_date.SelectedDate 不会返回 null。

这将在 dbnull 中插入一个空值。 Date 是一个接受 null 的 smalldatetime

插入 [测试].[dbo].[日期范围] ([ID] ,[日期]) 价值观 ('1000',空) 去吧

【讨论】:

  • 你对这样的逻辑有想法吗?
  • datePicker1.SelectedDate.HasValue
  • 基本上给出了优秀作品的答案。但我不知道每个变量将如何成为“NULL”而不仅仅是值 NULL 。有人有想法吗?
  • SelectedDate 为空。在 SQL 插入中,字符串 null 用于表示 null。插入语句是文本,因此必须有某种方式来表示 null。在 .NET 中,您拥有具有 HasValue 等属性的对象。
  • 对不起我没看懂,Has Value 返回真/假,你怎么得到字符串NULL?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-07
  • 1970-01-01
  • 2014-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多