C# 来自多个组合框的日期时间

C# 来自多个组合框的日期时间,c#,C#,我正在尝试将我在表单上的许多组合框中的日期时间组合起来 从这张图中,您可以看到组合框的布局。 想知道什么是最好的方法,目前我有以下,但不确定它是正确的 string startdate = cmbMonthYear.Text + "-" + cmbMonth.SelectedIndex.ToString()+ "-" + cmbDay.Text + " "+ "07:00"; DateTime StartDate = DateTime.ParseExact(startdate, "yyyy-

我正在尝试将我在表单上的许多组合框中的日期时间组合起来

从这张图中,您可以看到组合框的布局。

想知道什么是最好的方法,目前我有以下,但不确定它是正确的

string startdate = cmbMonthYear.Text + "-" + cmbMonth.SelectedIndex.ToString()+ "-" + cmbDay.Text + " "+ "07:00";

DateTime StartDate = DateTime.ParseExact(startdate, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
我能做的最好的方法是什么

这应该行得通(如果您确定您的输入):


一个更好的方法可能是避免精确解析,并确保您拥有所需日期的最精确表示,最好是整数。您还需要设置组合框中项目的
值。您可能可以在将项目添加到这些组合框的代码中实现这一点

所以你会有这样的想法:

// Check your input here
// ...
int day = Convert.ToInt32(cmbDay.SelectedValue);
int month = Convert.ToInt32(cmbMonth.SelectedValue); // No need to have text in SelectedValue, just integer
int year = Convert.ToInt32(cmbMonthYear.SelectedValue);

DateTime StartDate = new DateTime(year, month, day, 7, 0, 0);

使用
DateTime.TryParse
方法也验证用户的输入。当您有时使用文本框而不是下拉列表时,这是一个很好的做法:

string startdate = cmbMonthYear.SelectedValue 
    + "-" + cmbMonth.SelectedValue
    + "-" + cmbDay.SelectedValue 
    + " 07:00";
DateTime StartDate;

if(!DateTime.TryParse(startdate, out StartDate){
  //invalid date, show a warning message (e.g. lblErrors.Text = "Start Date is not valid!";)
}else{
    //your date is parsed and valid :)
}

@AliRashidi或者,简单的问题更容易回答?
string startdate = cmbMonthYear.SelectedValue 
    + "-" + cmbMonth.SelectedValue
    + "-" + cmbDay.SelectedValue 
    + " 07:00";
DateTime StartDate;

if(!DateTime.TryParse(startdate, out StartDate){
  //invalid date, show a warning message (e.g. lblErrors.Text = "Start Date is not valid!";)
}else{
    //your date is parsed and valid :)
}