填充 aspx 页上的多个文本框,直到通用列表循环遍历
本文关键字:列表 遍历 循环 aspx 文本 填充 | 更新日期: 2023-09-27 18:33:48
在
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++;
}
}
}
}
}
}
}
}
在答案列表上做一个 foreach
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) {
foreach(Answer ans in AnswerList) {
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 = ans.Answer;
answerTextBox.ReadOnly = true;
}
}
}
}
}
}
}
}