本文介绍了循环遍历文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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 = ...;
}

这篇关于循环遍历文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 08:14