0
我正在創建一個調查頁面,其中包含可以是單選按鈕列表,複選框列表或文本框的問題和答案列表。這些控件使用Controls.Add動態添加到其ItemDataBound事件中的Repeater。無法找到中繼器中動態添加的控件的選定值
我已經設法渲染頁面,但是當我提交表單並迭代中繼器中的控件以獲取單選按鈕和文本框值的選定值時,FindControl返回null。我需要做些什麼來獲得選定的值?我試着迭代RepeaterItems,但也返回null。我嘗試過不同類型的FindControl,但它永遠不會解析控件類型。 它的工作原理,如果我在直放站加聲明的DataBinder這樣
<asp:Repeater ID="rptSurvey" runat="server" Visible="true" EnableViewState="true" >
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem, "Question") %>
</ItemTemplate>
</asp:Repeater>
不過,我想要動態添加控件,但在做這個我不能得到提交時selectedvalues。這是我的代碼的主要結構...
<html>
<asp:Repeater ID="rptSurvey" runat="server" Visible="true">
</asp:Repeater>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</html>
protected void Page_Load(object sender, EventArgs e)
{
...
if (!IsPostBack)
{
rptSurvey.DataSource = GetQuestions();
rptSurvey.DataBind();
}
...
}
protected void rptSurvey_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
string question = (DataBinder.Eval(e.Item.DataItem, "Question")).ToString();
litQuestion = new Literal();
litQuestion.Text = question;
RadioButtonList rblAnswer = (RadioButtonList)item;
rptSurvey.Controls.Add(rblAnswer);
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
...
Dictionary<int, string> answers = new Dictionary<int, string>();
try
{
var list = FindControls(rptSurvey, c => c is RadioButtonList || c is CheckBoxList || c is TextBox);
foreach (Control item in list)
{
QuestionId = int.Parse(Questions.Rows[list.IndexOf(item)][0].ToString());
if (item is TextBox)
{
TextBox txtAnswer = (TextBox)item;
answers.Add(QuestionId, txtAnswer.Text);
}
else if (item is RadioButtonList)
{
RadioButtonList rblAnswer = (RadioButtonList)item;
answers.Add(QuestionId, rblAnswer.SelectedItem.Text);
}
else if (item is CheckBoxList)
{
// Iterate through the Items collection of the CheckBoxList
string cblMultiAnswer = "";
for (int i = 0; i < cblAnswer.Items.Count; i++)
{
if (cblAnswer.Items[i].Selected)
{
cblMultiAnswer += cblAnswer.Items[i].Value + ",";
}
}
answers.Add(QuestionId, cblMultiAnswer);
}
}
bSurvey.BLInsertSurveyAnswers(answers, dateCreated, _userEmail);
}
}
public static List<Control> FindControls(Control parent, Predicate<Control> match)
{
var list = new List<Control>();
foreach (Control ctl in parent.Controls)
{
if (match(ctl))
list.Add(ctl);
list.AddRange(FindControls(ctl, match));
}
return list;
}
謝謝karlis,頁面和它的控制渲染好。當我嘗試枚舉控件以獲取它們的值爲null時。我想通過添加控件OnItemDataBound將照顧創建控制樹,並且據我所見,控制樹在那裏。我錯過了其他基本的東西嗎? – Brendan
你有沒有改變你的代碼來建立controltree總是?也許你更新你的代碼inital post .... – karlis
我又看了一下你的源代碼:rptSurvey.Controls.Add(rblAnswer) - >我不認爲這就好,你正在添加到中繼器,但你應添加到該項目, - > e.Item.Controls.Add(rblAnswer) – karlis