我有2个foreach循环,我的第一个循环在一个方法中,该方法在加载主窗体时启动,方法如下:
private void GetDateDay()
{
foreach (DateTimePicker Dater in this.ReminderPanel.Controls.OfType<DateTimePicker>())
{
label1.Text = "true";
DateTime DaterValue = Dater.Value;
DateList.Add(Dater.Value);
}
SundayTotal = DateList.Count(x => x.DayOfWeek == DayOfWeek.Sunday);
MondayTotal = DateList.Count(x => x.DayOfWeek == DayOfWeek.Monday);
TuesdayTotal = DateList.Count(x => x.DayOfWeek == DayOfWeek.Tuesday);
WednesdayTotal = DateList.Count(x => x.DayOfWeek == DayOfWeek.Wednesday);
ThursdayTotal = DateList.Count(x => x.DayOfWeek == DayOfWeek.Thursday);
FridayTotal = DateList.Count(x => x.DayOfWeek == DayOfWeek.Friday);
SaturdayTotal = DateList.Count(x => x.DayOfWeek == DayOfWeek.Saturday);
}
此方法不起作用,正如您所看到的,我更改了label.text,因为我想查看循环何时不起作用,我发现它可以工作,但在循环之后却无法工作,因为标签不起作用更改其文本。 我的理论是,因为我的主窗体中有很多控件,并且面板的控件按代码加载,所以方法循环返回null,因为该方法在面板控件加载之前进行检查,即使在调用UI加载方法。
面板代码:。
TaskUC Task = new TaskUC ();
ReminderPanel.Controls.Add(Task);
(TaskUC包含DateTimePicker-因此面板包含TaskUC,其中TaskUC包含DateTimePicker)。
答案 0 :(得分:2)
该控件集合仅包括直属子级,并且您的日期选择器更深入地嵌入了一层。您需要遍历ReminderPanel包含的控件中包含的所有控件。
代替
foreach (DateTimePicker Dater in this.ReminderPanel.Controls.OfType<DateTimePicker>())
{
label1.Text = "true";
DateTime DaterValue = Dater.Value
DateList.Add(Dater.Value);
}
尝试一下(没有foreach
循环):
DateList = this.ReminderPanel.Controls //Get all controls on the panel
.SelectMany( c => c.Controls ) //Get all controls contained in those controls
.OfType<DateTimePicker>() //Only include DateTimePickers
.Select( dtp => dtp.Value ) //Get the value
.ToList(); //Make it a list
这将为您创建DateList
,而不会循环。