循环文本框

Tar*_*ryn 15 .net c# textbox winforms

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

DateTextBox0
DateTextBox1 ...
DateTextBox37
Run Code Online (Sandbox Code Playgroud)

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

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();
}
Run Code Online (Sandbox Code Playgroud)

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

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

aba*_*hev 37

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

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);
}
Run Code Online (Sandbox Code Playgroud)

用法:

var allTextBoxes = this.GetChildControls<TextBox>();
foreach (TextBox tb in allTextBoxes)
{
    tb.Text = ...;
}
Run Code Online (Sandbox Code Playgroud)

  • +1 - 这几乎就是我要发布的代码. (7认同)
  • 看起来像最优雅的解决方案,但我得到错误:"TControl --->无法找到类型或命名空间名称'TControl'(您是否缺少using指令或程序集引用?)".我搜索过MSDN,但没找到那个班级.该怎么办? (2认同)

JAi*_*iro 6

您可以循环显示表单中的所有控件,如果它是"文本框",则逐一返回它们的完整列表.

public List GetTextBoxes(){   
    var textBoxes = new List();   
        foreach (Control c in Controls){   
            if(c is TextBox){   
                textBoxes.add(c);   
        }   
    }   
return textBoxes;   
}
Run Code Online (Sandbox Code Playgroud)


Zat*_*h . 5

由于这篇文章似乎会时不时地重新出现,并且由于上面的解决方案没有在控件内部(例如在组框中)找到控件,因此这将找到它们。只需添加您的控件类型:

public static IList<T> GetAllControls<T>(Control control) where T : Control
{
    var lst = new List<T>();
    foreach (Control item in control.Controls)
    {
        var ctr = item as T;
        if (ctr != null)
            lst.Add(ctr);
        else
            lst.AddRange(GetAllControls<T>(item));
    }
    return lst;
}
Run Code Online (Sandbox Code Playgroud)

及其用途:

var listBoxes = GetAllControls<ListBox>(this);
foreach (ListBox lst in listBoxes)
{
    //Do Something
}
Run Code Online (Sandbox Code Playgroud)