有没有办法我可以将DateTimePicker默认为下周五,所以它应该总是默认为星期五,它将在下周出现。即使他们选择了本周的周五。
我有以下代码作为我的尝试:但是在修改时
if (selectedDate.DayOfWeek != DayOfWeek.Friday)
至:
if (selectedDate.DayOfWeek == DayOfWeek.Friday)
它循环播放。如下所示将其设置为星期五然后点击更改的事件并显示为星期五,因此(selectedDate.DayOfWeek == DayOfWeek.Friday)
代码也会导致无限循环。
var dtp = pSender as DateTimePicker;
var selectedDate = dtp.Value;
if (selectedDate.DayOfWeek != DayOfWeek.Friday)
{
var offset = (int)DayOfWeek.Friday - (int)selectedDate.DayOfWeek + 7; //Friday after current week.
var friday = selectedDate + TimeSpan.FromDays(offset);
dtp.Value = friday;
}
感谢您的时间,
答案 0 :(得分:3)
如果您处理DateTimePicker.ValueChanged
事件并在那里更改值,那么它是一个无限循环。您应该只在Form
,Form_Load
事件的构造函数中执行此操作,或者您必须检查它是否以编程方式完成:
private bool dtpChangedManually = false;
protected void Dtp_ValueChanged(Object sender, EventArgs e)
{
if (dtpChangedManually)
{
dtpChangedManually = false;
return;
}
dtpChangedManually = true;
var pSender = (DateTimePicker) sender;
int daysUntilFridDay = ((int)DayOfWeek.Friday - (int)pSender.Value.DayOfWeek + 7) % 7;
if(daysUntilFridDay == 0) daysUntilFridDay = 7;
DateTime nextFriday = pSender.Value.AddDays(daysUntilFridDay);
pSender.Value = nextFriday;
}