在占位符中查找控件
本文关键字:控件 查找 占位符 | 更新日期: 2023-09-27 17:48:59
我使用AJAX使一个用户控件,其中包含一个面板,根据条件包含标签和RadioButtonList或CheckBoxList。在.aspx页面中有一个占位符,该控件应该在其中。我需要从占位符找到列表我试过了:
public static int id = 1;
QuestionPanelControl q1 ;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadQuestionPanelControl();
}
}
//Next Button
protected void Button1_Click(object sender, EventArgs e)
{
id++;
if (id <= 10)
{
//LoadQuestionPanelControl();
PlaceHolder p = (PlaceHolder)Page.FindControl("PlaceHolder1");
QuestionPanelControl c1 = (QuestionPanelControl)p.FindControl("QuestionPanelControl1");
// QuestionPanelControl c1 = (QuestionPanelControl)p.FindControl("Panel_Question");
RadioButtonList rb = c1.ChildRadioButtonList;
if (rb.SelectedIndex == 0)
{
//DB
}
else if (rb.SelectedIndex == 1)
{
//DB
}
else
{
Lsb_Unanswered.Items.Add("Question #" + id);
}
LoadQuestionPanelControl();
}
}
public void LoadQuestionPanelControl()
{
Session.Add("ID",id);
q1= new QuestionPanelControl();
q1.ID = "QuestionPanelControl1";
Control c = Page.LoadControl("QuestionPanelControl.ascx");
PlaceHolder1.Controls.Clear();
PlaceHolder1.Controls.Add(c);
}
当我使用断点时,我发现p的Controls属性为0。
注意:childadiobuttonlist是QuestionPanelControl中的一个属性。什么建议…
试试下面的代码:
PlaceHolder p = (PlaceHolder)FindControlRecursive(Page, "PlaceHolder1");
public static Control FindControlRecursive(Control ctrl, string controlID)
{
if (string.Compare(ctrl.ID, controlID, true) == 0)
{
// We found the control!
return ctrl;
}
else
{
// Recurse through ctrl's Controls collections
foreach (Control child in ctrl.Controls)
{
Control lookFor = FindControlRecursive(child, controlID);
if (lookFor != null)
return lookFor; // We found the control
}
// If we reach here, control was not found
return null;
}
}
EDIT:
public void LoadQuestionPanelControl()
{
Session.Add("ID",id);
Control c = Page.LoadControl("QuestionPanelControl.ascx");
var q1= c as QuestionPanelControl;
if(q1 != null)
{
q1.ID = "QuestionPanelControl1";
PlaceHolder1.Controls.Clear();
PlaceHolder1.Controls.Add(q1);
}
}
,看看控件是否。占位符的计数不是0。