2011-02-18 52 views
0

我有一個組合框,其值爲1-25。
我也有2個datetimepickers顯示時間值。加上整數並加上小時值

如果我從組合框中爲第一個datetimepicker和2選擇10:00 AM,我希望第二個datetimepicker中的結果爲12:00 PM

這怎麼辦?

回答

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

@Student Nope。它不會影響firstDatePicker的值。結帳[AddHours()](http://msdn.microsoft.com/en-us/library/system.datetime.addhours.aspx)文檔。 – 2011-02-18 15:36:40

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; 
}