简体   繁体   English

C#将日期从字符串加载到datetimepicker

[英]C# Load a date from a string into a datetimepicker

I'm trying to update an old c# program that I inherited along the way. 我正在尝试更新沿途继承的旧c#程序。 Not big changes, just adding some new fields etc. I'm using Visual Studio 2008. 没有太大的变化,只是添加了一些新字段等。我正在使用Visual Studio 2008。

Specifically I'm trying to read a date time from an SQL Table and insert it into a DateTimePicker so the user can read / modify it on the screen. 具体来说,我试图从SQL表读取日期时间并将其插入DateTimePicker,以便用户可以在屏幕上读取/修改它。

I have tried a few different ways to do this but the code below seems like the most sensible. 我尝试了几种不同的方法来执行此操作,但是下面的代码似乎是最明智的。

I have read the date time string into a datetime variable from my SQL database. 我已经从SQL数据库中将日期时间字符串读入datetime变量中。

I can display the value in a message box no problem but when I try and load it into the dateTimePicker control I get an exception. 我可以在消息框中显示值,没问题,但是当我尝试将其加载到dateTimePicker控件时,出现异常。

The date displayed in the message box looks like this. 消息框中显示的日期如下所示。 24/06/2015 12:00:00 AM (Australian Date format is correct and I don't care what the time is) 2015年6月24日上午12:00:00(澳大利亚日期格式正确,我不在乎现在的时间)

"Object Reference not set to an instance of an object" _COMPlusExceptionCode = -532459699 “对象引用未设置为对象的实例” _COMPlusExceptionCode = -532459699

while (sqlDR.Read())
{
    this.textBoxFixedAmountStreetNumber.Text = sqlDR["lStreetNumber"].ToString() + sqlDR["sStreetNumberSuffix"].ToString();
    this.textBoxFixedAmountStreetName.Text = sqlDR["sStreet"].ToString();
    this.textBoxFixedAmountSuburb.Text = sqlDR["sTown"].ToString();
    DateTime dateString = Convert.ToDateTime(sqlDR["dFixedAmountEndDate"].ToString());
    MessageBox.Show("dFixedAmountEndDate=" + dateString, "Debug", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
    this.dateTimePickerFixedAmountEndDate.Value = dateString;
}

I'm probably the worlds oldest newbie because I do mostly sysadmin and never get to concentrate on a single programing language. 我可能是世界上最古老的新手,因为我主要是sysadmin,而且从不专心于单一编程语言。 :) :)

Any ideas on what I'm doing wrong is much appreciated. 任何关于我做错事情的想法都值得赞赏。

Thanks David 谢谢大卫

This should do it: 应该这样做:

var date_as string = "24/06/2015 12:00:00 AM";
DateTime date ;

DateTime.TryParse(d, out date);
// date now holds your date

Edit : 编辑
As other comments and Matt's answer suggest, you don't really need to parse a string (so the above even though correct, is probably not what you want). 正如其他评论和Matt的答案所暗示的那样,您实际上不需要解析字符串(因此,即使正确,上述内容也可能不是您想要的)。

If you do that you can use the bool result = DateTime.TryParse(d, out date); 如果这样做,则可以使用bool result = DateTime.TryParse(d, out date); and if the result is false assign a fake date (or better, when you define date, you can do: DateTime date = new DateTime(); so if the parsing fails, you'll still have a valid date. 并且如果结果为false分配一个伪造的日期(或者更好的是,在定义日期时,可以执行以下操作: DateTime date = new DateTime();因此,如果解析失败,您将仍然拥有一个有效日期。

You can achieve the same by testing for null if you go with the other approach. 如果采用其他方法,则可以通过测试null来实现相同目的。 Either way, you should be aware of the perils :) 无论哪种方式,您都应该意识到危险:)

This line is bad: 这行是不好的:

DateTime dateString = Convert.ToDateTime(sqlDR["dFixedAmountEndDate"].ToString());

This is its replacement: 这是它的替代品:

DateTime fixedAmountEndDate = (DateTime) sqlDR["dFixedAmountEndDate"];

Never convert to a string when you don't have to, and use names that make sense. 不必在不需要时转换为字符串,并使用有意义的名称。

However, if you're getting "Object Reference not set to an instance of an object" - That's a NullReferenceException . 但是,如果您获取的"Object Reference not set to an instance of an object" ,则为NullReferenceException Chances are that one of your SQL fields is nullable in the database and contains a null value. 您的SQL字段之一在数据库中可能为空,并且包含空值。 You need to test for that condition explicitly, as a DateTime can't be nullable, and neither can DateTimePicker.Value . 您需要显式测试该条件,因为DateTime不能为空, DateTimePicker.Value也不可以。

if (sqlDR["dFixedAmountEndDate"] == DBNull.Value)
    // do something.  Perhaps hide the field, etc.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM