我有一个用户控件(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(其中一些可以添加到Control1上的placeHolder中):
<%@ 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 :(得分: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"];
答案 1 :(得分: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");
}
}
}