2011-07-12 97 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"];