2011-04-04 82 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