作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我有一个 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 循环,我必须循环主要控件(面板),然后循环面板上的控件。它开始变得复杂。
关于如何将这个值分配给文本框有什么建议吗?
最佳答案
要递归地获取指定类型的所有控件和子控件,请使用此扩展方法:
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 = ...;
}
关于c# - 循环遍历文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4863051/
我是一名优秀的程序员,十分优秀!