gpt4 book ai didi

c# - 循环遍历文本框

转载 作者:可可西里 更新时间:2023-11-01 03:12:05 24 4
gpt4 key购买 nike

我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com