添加整数和小时值

时间:2011-02-18 15:16:09

标签: c# .net

我有一个组合框,其值为1-25 我还有2个显示时间值的datetimepickers。

如果我从组合框中为第一个datetimepicker和10:00 AM选择2,我希望第二个datetimepicker中的结果为12:00 PM

如何做到这一点?

3 个答案:

答案 0 :(得分:3)

secondDatePicker.Value = firstDatePicker.Value.AddHours(Convert.ToInt32(comboBox1.SelectedValue));

答案 1 :(得分:2)

只需查看MSDN:http://msdn.microsoft.com/en-us/library/system.datetime.aspx

使用AddHours方法。

这样的事情:

int iIncrement = int.Parse(combobox.SelectedValue);
Datetime dt = firstDateTimePicker.value;
secondDateTimePicker.value = dt.AddHours(iIncrement );

答案 2 :(得分:1)

假设您有一个包含两个DateTimePicker s(dateTimePicker1和DateTimePicker2)和一个包含指定值的ComboBox的表单,请将一个事件处理程序添加到组合框的SelectedIndexChanged事件中,如下所示:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    // Get the DateTime from the first picker
    var currentDateTime = dateTimePicker1.Value;
    // Get the number of Hours to add to the DateTime
    var hoursToAdd = Convert.ToInt32(comboBox1.SelectedItem);
    // Add the hours to the DateTim
    var newDateTime = currentDateTime.AddHours(hoursToAdd);
    // Tell dateTimePicker2 to use the DateTime that has the hours added
    dateTimePicker2.Value = newDateTime;
}