浏览所有文本框,组合框...并清除其内容 [英] Go through all textboxes, comboboxes,... and clear their content

查看:122
本文介绍了浏览所有文本框,组合框...并清除其内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何遍历所有控件,而不管它们位于面板或组框中,...
现在我有了这样的东西:
我添加了另一个类,并且在该类中是代码:

How to loop through all the controls regardless of them being on a panel or groupbox,...
Now i have something like this:
I added another class and in this class is the code:

 public void New(Form1 f1)
        {  
 foreach (Control c in f1.Controls)
            {

                if (c is TextBox || c is ComboBox)
                {
                    c.Text = "";
                }
}

            }


推荐答案

foreach(Control ctrl in this.Controls)
{
    if(ctrl is TextBox)
        string str = ((TextBox)ctrl).Text;
    
    if(ctrl is ComboBox)
        string str = ((ComboBox) ctrl).SelectedItem.ToString();
    
    // and so on...
}


-KR


-KR


您是正确的:此处的其他响应不涉及表单中的控件内部容器控件,例如Panel和GroupBox.

若要在窗体上查找所有TextBox和ComboBox,无论它们在容器控件"中的嵌套"程度如何深",都需要进行递归搜索.

在回答先前的质量检查问题时,我提供了代码,以使用Eric Lippert建议的基于堆栈的"技术以递归方式在窗体上构建所有控件的集合:[
You are correct: the other responses here do not deal with Controls inside Container Controls, like Panel, and GroupBox, in the Form.

To find all the TextBoxes, and ComboBoxes, on the Form, no matter how "deeply" they are "nested" inside Container Controls, requires a recursive search.

In my response to a previous QA question I provided code for recursively building a collection of all Controls on a Form using the "stack-based" technique recommended by Eric Lippert: [^].

You can take that code and use it, like this:
// requires Linq

// clear Text in all TextBoxes
foreach (TextBox theTextBox in (SpecialMethods.GetAllControls(this)).OfType<TextBox>().ToList())
{
    theTextBox.Clear();
}

// clear ComboBoxItems in all ComboBoxes
foreach (ComboBox theComboBox in (SpecialMethods.GetAllControls(this)).OfType<ComboBox>().ToList())
{
    theComboBox.Items.Clear();
}


foreach (Control objControl in this.Controls)
            {

                if (objControl.GetType() == typeof(TextBox))
                {
                    TextBox objTxt = (TextBox)objControl;
                    objTxt.Text = "";
                }
            }




尝试以其他方式进行其他控制.
谢谢




Try others control with same way.
Thanks


这篇关于浏览所有文本框,组合框...并清除其内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆