【发布时间】:2012-05-09 11:59:47
【问题描述】:
有什么好的方法可以在一个aspx页面上填充固定数量的文本框,直到通用列表被循环遍历并填充了它可以填充的所有空文本框?
我现在有以下内容,但如果列表中的答案较少,那么有文本框我会收到 outOfBoundException。
else if(!IsPostBack) {
Groups group = new Groups();
List<Answers> AnswerList = new List<Answers>();
//Get the group since the session isn't null
group = group.getGroupbyId(int.Parse(Session["group_Id"].ToString()));
//Get the list of answers of the group
AnswerList = Answers.retrieveAnswersBygroupIdandPageNumber(group.Group_Id, pageNumberLab);
if (AnswerList.Count != 0) {
while (TextAnswerNumber < AnswerList.Count) {
ContentPlaceHolder cph = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
foreach (Control control in cph.Controls) {
if (control is Panel) {
Panel panel = (Panel)control;
foreach (Control controlInPanel in panel.Controls) {
//If the control is a textbox
if (controlInPanel is TextBox && controlInPanel.ID.Contains("txtAnswer")) {
//And if the control ID containst txtAnswer
//IMPORTANT: If next programmer adds another textbox for an answer textbox the ID must be in the form txtMember*".
TextBox answerTextBox = (TextBox)controlInPanel;
// Check if the textbox is empty
if (answerTextBox.Text == "") {
//If it is, fill it with the answer that group filled in when it previously answered this question.
answerTextBox.Text = AnswerList[TextAnswerNumber].Answer;
answerTextBox.ReadOnly = true;
TextAnswerNumber++;
}
}
}
}
}
}
}
}
【问题讨论】:
-
我不喜欢你的代码,但真正的快速解决方法是将
&& (TextAnswerNumber < AnswerList.Count)添加到 if(control isPanel)` 检查中。 -
您能否详细说明为什么您不喜欢这些代码。我知道这与问题没有直接关系,但它可能会更清楚。并感谢它的工作原理。我以为我已经尝试过了但无济于事,但似乎没有。编辑:现在我记得,我尝试了您输入的内容,但如果我使用 while 则不是常规的。
标签: c# asp.net loops generic-list