多组合框的日期时间

时间:2014-02-24 12:54:25

标签: c#

我正在尝试组合我在表单上的一些组合框中的DateTime。

从这张图片中,您可以看到如何布置组合框。 enter image description here

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

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

DateTime StartDate = DateTime.ParseExact(startdate, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);

我能做到这一点的最佳方式是什么?

3 个答案:

答案 0 :(得分:1)

更好的方法可能是避免解析精确,并确保您拥有所需日期的最准确表示,最好是整数。您还需要在组合框中设置Value - 部分项目。您可以在将项添加到这些组合框的代码中执行此操作。

所以你会有类似的东西:

// 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);

答案 1 :(得分:0)

这应该有用(如果你确定你的输入):

var date = new DateTime(int.Parse(cmbMonthYear.Text), cmbMonth.SelectedIndex, int.Parse(cmbDay.Text), 7, 0, 0);

答案 2 :(得分: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 :)
}