2011-04-04 83 views
3

我使用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的属性0.

注意:ChildRadioButtonList是QuestionPanelControl中的一个属性。 任何建议...

+0

如何以及何时将QuestionPanelControl添加到占位符? – 2011-04-04 19:02:22

+0

我已编辑代码:) – noor 2011-04-04 19:08:38

回答

3

试试这个代码:

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; 
} 
} 
+0

我已经尝试过,但我不知道如何调用它。我应该写什么而不是Control ctrl prameter? – noor 2011-04-04 19:21:39

+0

@noor:你应该写Page或这 – vvk 2011-04-04 19:27:38

+0

你的意思是说这个函数将在.ascx页面中? – noor 2011-04-04 19:36:31

0

编辑:

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); 
     } 

    } 

,看看Controls.Count的占位比0

以外的东西
+0

我试过了,但是在向控制面板中添加radioButtonList的时候抛出异常。 – noor 2011-04-04 19:20:19

+0

未将对象引用设置为对象的实例异常。 – noor 2011-04-04 19:22:17

+0

你可以发布发生此异常的用户控制代码部分吗? – 2011-04-04 19:23:34