通过面板C#中的文本框控件进行迭代

时间:2010-08-26 22:07:15

标签: c# asp.net textbox iteration

我见过很多其他类似问题,但我在这里的逻辑中找不到这个缺陷。任何帮助将不胜感激。

我有一个Panel,我已经添加了许多标签和文本框控件,即:

myPanel.Controls.Add(txtBox);

这些控件是在迭代方法之前调用的方法中创建和添加的。

我想遍历每个文本框并使用其Text属性作为另一种方法中的参数,但我没有任何运气。这是我尝试迭代:

public void updateQuestions()
{
    try
    {
        foreach (Control c in editQuestionsPanel.Controls)
        {
            if (c is TextBox)
            {
                TextBox questionTextBox = (TextBox)c;

                string question = questionTextBox.Text;

                writeNewQuestionToTblQuestions(question);
            }
        }
    }
    catch (Exception err)
    {
        Console.WriteLine(err.Message);
    }
}

我遇到的问题是,当我到达此updateQuestions()方法时,控件不在Panel中。这是涉及的过程:

单击commandButton并从数据库中读取问题,对于每个问题调用一个方法,该方法将2个标签和一个文本框添加到editQuestionsPanel.Controls。此面板位于PlaceHolder中,然后可以看到。

单击PlaceHolder中的按钮时,将调用updateQuestions()方法并且editQuestionsPanel.Controls.Count = 1.由于DB中大约有12个问题,因此应该是36左右。是类型:

System.Web.UI.LiteralControl  

它不包含任何控件。

我确信在生命周期中,Panel的控件正在被清除,但我不知道如何跨越生命周期。我有一个Page_load方法,只要单击一个按钮就会调用它但是一旦调用了updateQuestions()的按钮,editQuestionsPanel.Controls.Count已经回到1,所以在此之前必须清除它,但我不知道如何纠正这个...

你可以给予任何帮助我解决这个问题的帮助将非常感激 - 它会杀了我!

6 个答案:

答案 0 :(得分:3)

这仅从集合控件中选择TextBox类型。

(与control is TextBox(control as TextBox) != null相同)

如果控件包含在editQuestionsPanel.Controls

using System.Linq;

IEnumerable<TextBox> textBoxes = editQuestionsPanel.Controls.OfType<TextBox>();    
foreach (TextBox textBox in textBoxes)
{
    // do stuff
}

要选择所有子控件,请使用下一个扩展方法:

public static IEnumerable<T> GetChildControls<T>(this Control control) where T : Control
{
    var children = control.Controls.OfType<T>();
    return children.SelectMany(c => GetChildControls<T>(c)).Concat(children);
}

使用:

IEnumerable<TextBox> textBoxes = editQuestionsPanel.GetChildControls<TextBox>();

答案 1 :(得分:2)

当您动态添加控件时,您需要在每个请求上执行此操作 - asp.net不会为您执行此操作!

在Init或Load阶段添加控件,然后填充回发值。

答案 2 :(得分:1)

经常犯的错误:Container.Controls仅包含此容器中的第一级子控件。即:PanelA中的TextBox1,PanelB中的PanelA,您无法在PanelB.Controls中获取TextBox1。

我的解决方案是编写扩展方法:

public static IEnumerable<Control> AllControls(this Control ctl)
{
   List<Control> collection = new List<Control>();
   if (ctl.HasControls())
   {
       foreach (Control c in ctl.Controls)
       {
             collection.Add(c);
             collection = collection.Concat(c.AllControls()).ToList();
       }
   }
   return collection;
}

现在TextBox1位于PanelB.AllControls()。要使用PanelB.AllControls().OfType<TextBox>()

过滤所有类型的控件

答案 3 :(得分:0)

你可以这样做:

var questions = from tb in editQuestionsPanel.Controls.OfType<TextBox>()
                select tb.Text;

foreach(var question in questions)
{
    writeNewQuestionToTblQuestions(question);
}

答案 4 :(得分:0)

如果其他答案没有帮助,请尝试执行代码但添加递归。如果是editQuestionsPanel =&gt;您的代码将不起作用Panel =&gt;文本框

答案 5 :(得分:0)

试试这个

        int Count = 0;
        foreach (Control ctr in Panel1.Controls)
        {
            if (ctr is TextBox)
                Count++;
        }