2011-07-12 141 views
0

我有一個用戶控件(Control1),它有一個佔位符,可能包含幾個其他用戶控件(屬於同一類型 - 見下文),這些控件是動態添加的。點擊位於控件1中的按鈕時,如何導航用戶控件層次結構以查找嵌套控件集的值?如何在嵌套用戶控件中查找嵌套控件

控制1:

<%@ Control Language="C#" AutoEventWireup="True" CodeBehind="Control1.ascx.cs" Inherits="Control1" %> 
<%@ Reference Control="Control2.ascx" %> 

<div id="div1"> 
    <div id="divPh"><asp:PlaceHolder ID="phControls" runat="server" /></div> 
<div id="divContinue"><asp:Button ID="btnContinue" Text="Continue" OnClick="submit_Click" runat="server" /></div> 
</div> 

代碼後面爲Control1.aspx:

protected void submit_Click(object sender, EventArgs e) 
{ 
    // iterate through list of divControl2 controls and find out which radio button is selected 
    // for example, there may be 3 divControl2's which are added to the placeHolder on Control1, rdoBth1 might be selected on 2 of the controls 
    // and rdoBtn2 might be selected on 1 - how do I navigate this control structure? 
} 

控制2(其中一些可以被添加到對控制1佔位符):

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Control2.ascx.cs"  Inherits="Control2" %> 
    <div id="divControl2"> 
     <p><strong><asp:RadioButton ID="rdoBtn1" GroupName="Group1" Checked="true" runat="server" /> Check this</strong></p> 
     <p><strong><asp:RadioButton ID="rdoBtn2" GroupName="Group1" Checked="false" runat="server" /> No, check this one</strong></p> 
    </div> 

回答

0

檢查下面的代碼,讓我知道,如果您有任何疑問。

protected void submit_Click(object sender, EventArgs e) 
    { 
     for (int count = 0; count < phControls.Controls.Count; count++) 
     { 
      UserControl uc = (UserControl)(phControls.Controls[count]); 
      if (uc != null) 
      { 
       RadioButton rdoBtn1 = new RadioButton(); 
       RadioButton rdoBtn2 = new RadioButton(); 
       rdoBtn1 = (RadioButton)(uc.FindControl("rdoBtn1")); 
       rdoBtn2 = (RadioButton)(uc.FindControl("rdoBtn2")); 
       if (rdoBtn1.Checked == true) 
       { 
        Response.Write("1st checked "); 
       } 
       else if (rdoBtn2.Checked == true) 
       { 
        Response.Write("2nd checked"); 
       } 

      } 
     } 
0

這不是世界上最好的設計,但是你可以用一些相對容易的方法來完成你想要的。問題在於這些控件所在的頁面必須對動態添加的控件的內部工作有深入的瞭解。而且,您將希望他們實現一個通用的抽象類或接口,以便您可以按類型查找正確的類。

以下代碼假定您已經創建了用於訪問內部控件值的屬性,而不必自己引用內部控件。當您使用任何類型的控件時,這只是一個好習慣。

protected void submit_Click(object sender, EventArgs e) { 
    foreach (var control in phControls.Controls) { 
     IMySpecialControl mySpecialControl = control as IMySpecialControl; 

     if (mySpecialControl != null) { 
      // access some properties (and probably need a cast to the specific control type :(
     } 
    } 
} 

相反,爲什麼不只是通過Request.Form集合訪問字段?

string rdoBtn1Value = Request.Form["rdoBtn1"];