问题描述
我有一个WinForms应用程序,有37个文本框在屏幕上。每一个顺序编号:
I have a winforms app that has 37 textboxes on the screen. Each one is sequentially numbered:
DateTextBox0
DateTextBox1 ...
DateTextBox37
我想遍历文本框和值分配给每一个:
I am trying to iterate through the text boxes and assign a value to each one:
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循环,我通过主控制(面板),然后通过面板上的控制回路必须循环。它开始变得复杂了。
Let me clarify that these textboxes appear on separate panels (37 of them). So in order for me to loop through using a foreach, I have to loop through the primary controls (the panels), then loop through the controls on the panels. It starts getting complicated.
这是我怎么可以把这个值赋给文本框有什么建议?
Any suggestions on how I can assign this value to the textbox?
推荐答案
要获得所有的控制和子控制递归指定类型的,使用这个扩展方法:
To get all controls and sub-controls recursively of specified type, use this extension method:
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 = ...;
}
这篇关于通过文本框环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!