如何将 3 个文本框值合并到一个 Date 中以写入 C# 中的 dataGridView

How can I merge 3 textbox values into a single Date to write into a dataGridView in C#

我是 C# 的新手,我正在制作一个可以节省不同时间的程序。我想知道如何用三个文本框字符串写出一个日期(通过分别输入日、月和年的值)以及如何为时间做同样的事情(写小时和分钟)。

int a = int.Parse(textBox_DDVzleta.Text);
int b = int.Parse(textBox_MMVzleta.Text);
int c = int.Parse(textbox_YYVzleta.Text);

DateTime Vzlet = new DateTime(a, b, c);

我试过将它转换成一个整数,但它不起作用。

有一个所谓的 DateTime Constructor(MSDN 参考)。您可以使用给定的年月日整数对其进行初始化,它会为您创建日期时间对象。

DateTime date1 = new DateTime(2010, 8, 18);

在这种情况下你可以这样做

DateTime date1 = new DateTime(int.Parse(textBox_DDVzleta.Text), int.Parse(textBox_MMVzleta.Text), int.Parse(textbox_YYVzleta.Text));

结果见下方截图。

更新

我也试过你先转换为 int 的方法。

int a = int.Parse("30");
int b = int.Parse("01");
int c = int.Parse("2016");

DateTime date2 = new DateTime(c, b, a); // new DateTime(year, month, day)
Console.WriteLine(date2.ToString());

结果:

我认为你传递的参数位置错误。

您使用 DateTime(year, month, day) 构造函数,但将它们作为 DateTime(day, month, year) 传递给此构造函数。

只需更改您的参数位置即可;

DateTime Vzlet = new DateTime(c, b, a);

how can I do the same for Time (write the hours and minutes).

如果您指的是 TimeSpanTime,您也可以使用它的 TimeSpan(hour, minute, second) 构造函数。

TimeSpan ts = new TimeSpan(hour, minute, 0);

您可以通过使用字符串类型变量和连接来实现。 示例:

string x = a.tostring()+b.tostring()+c.tostring();

for values between spaces 你可以这样写。

string x = a.tostring() + " " + b.tostring() + " " + c.tostring();