通过面板C#中的文本框控件进行迭代
我见过很多其他类似问题,但我在这里找不到我的逻辑中的缺陷。 任何帮助将不胜感激。
我有一个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左右.Three中的一个控件是类型:
System.Web.UI.LiteralControl
它不包含任何控件。
我确信在生命周期中,Panel的控件正在被清除,但我不知道如何跨越生命周期。 我有一个Page_load方法,只要单击一个按钮就会调用它但是一旦调用了updateQuestions()的按钮,editQuestionsPanel.Controls.Count已经回到1,所以必须在此之前清除但我不知道如何纠正这个……
任何帮助你可以帮助我解决这个问题将不胜感激 – 它杀了我!
当您动态添加控件时,您需要在每个请求上执行此操作 – asp.net不会为您执行此操作!
在Init或Load阶段添加控件,然后将使用回发值填充它们。
这仅从集合控件中选择TextBox类型。
(与control is TextBox
相同的control is TextBox
或(control as TextBox) != null
)
如果控件包含在editQuestionsPanel.Controls
:
using System.Linq; IEnumerable textBoxes = editQuestionsPanel.Controls.OfType (); foreach (TextBox textBox in textBoxes) { // do stuff }
要选择所有子控件,请使用下一个扩展方法:
public static IEnumerable GetChildControls (this Control control) where T : Control { var children = control.Controls.OfType (); return children.SelectMany(c => GetChildControls (c)).Concat(children); }
使用:
IEnumerable textBoxes = editQuestionsPanel.GetChildControls ();
经常犯的错误: Container.Controls
只包含此容器中的第一级子控件。 即:PanelA中的TextBox1,PanelB中的PanelA,您无法在PanelB.Controls中获取TextBox1。
我的解决方案是编写扩展方法:
public static IEnumerable AllControls(this Control ctl) { List collection = new List (); 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
过滤所有类型的控件PanelB.AllControls().OfType
如果其他答案没有帮助,请尝试执行代码但添加递归。 如果是editQuestionsPanel => Panel => Textbox,您的代码将无效
你可以这样做:
var questions = from tb in editQuestionsPanel.Controls.OfType() select tb.Text; foreach(var question in questions) { writeNewQuestionToTblQuestions(question); }
试试这个
int Count = 0; foreach (Control ctr in Panel1.Controls) { if (ctr is TextBox) Count++; }