小编典典

遍历文本框

c#

我有一个Winforms应用程序,该应用程序在屏幕上有37个文本框。每一个都按顺序编号:

DateTextBox0
DateTextBox1 ...
DateTextBox37

我试图遍历文本框并为每个文本框分配一个值:

int month = MonthYearPicker.Value.Month;
int year = MonthYearPicker.Value.Year;
int numberOfDays = DateTime.DaysInMonth(year, month);

m_MonthStartDate = new DateTime(year, month, 1);
m_MonthEndDate = new DateTime(year, month, numberOfDays);

DayOfWeek monthStartDayOfWeek = m_MonthStartDate.DayOfWeek;
int daysOffset = Math.Abs(DayOfWeek.Sunday - monthStartDayOfWeek);

for (int i = 0; i <= (numberOfDays - 1); i++)
{
 //Here is where I want to loop through the textboxes and assign values based on the 'i' value
   DateTextBox(daysOffset + i) = m_MonthStartDate.AddDays(i).Day.ToString();
}

让我澄清一下,这些文本框出现在单独的面板上(其中37个)。因此,为了使我能够使用foreach进行遍历,我必须遍历主要控件(面板),然后遍历面板上的控件。它开始变得复杂。

关于如何将该值分配给文本框的任何建议?


阅读 425

收藏
2020-05-19

共1个答案

小编典典

若要递归获取所有指定类型的控件和子控件,请使用以下扩展方法:

public static IEnumerable<TControl> GetChildControls<TControl>(this Control control) where TControl : Control
{
    var children = (control.Controls != null) ? control.Controls.OfType<TControl>() : Enumerable.Empty<TControl>();
    return children.SelectMany(c => GetChildControls<TControl>(c)).Concat(children);
}

用法:

var allTextBoxes = this.GetChildControls<TextBox>();
foreach (TextBox tb in allTextBoxes)
{
    tb.Text = ...;
}
2020-05-19