在 datetimepicker C# 中将字符串解析为日期时间

Parsing string to datetime inside datetimepicker C#

我有一个连接到 Oracle 数据库的 C# 应用程序,还有一个像这样的 table Table

我创建了一个 MouseDoubleClick 事件,用于将数据选择到下面的字段中,我想将日期显示到第一个 datetimepicker 中,如图所示。在数据库中,特定日期设置为 Varchar,因此会弹出问题,我需要对其进行解析,以便将其显示在此日期时间选择器中。那么我究竟要如何进行解析呢?

鼠标双击事件:

ComboBox1.SelectedValue = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
comboBox2.Text = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
dateTimePicker1.Text = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();

在 datetimepciker 代码行中弹出错误消息。

您应该分配给 DateTimePicker class 的 "Value" 属性。

此外,您需要先将日期解析为 DateTime 对象,然后才能将其传入。像这样应该可以解决问题:

ComboBox1.SelectedValue = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
comboBox2.Text = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();

String s = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
//culture is set to british based on your date format
DateTimeFormatInfo culture = (new CultureInfo("en-GB")).DateTimeFormat;
DateTime dt; //declare variable to hold our datetime
//since this is DB data, use "tryparse" as it may not be formatted properly
if (DateTime.TryParse(s, culture, DateTimeStyles.None,out dt))
    dateTimePicker1.Value = dt;