ASP.NET有没有更好的办法找到其他的控制范围内的控制? [英] ASP.NET Is there a better way to find controls that are within other controls?
问题描述
目前,我有一个ascx控件内部下拉。我需要从后面上的另一个ASCX是在同一页上的code之内发现它。它的值被用作一个参数,以一个ObjectDataSource上ASCX#2。我目前正在使用这个难看的片片code的。它的工作原理,但我意识到,如果conrtol为了要改变或各种其他的东西,它不会是我在哪里期待。有没有人有任何意见,我应该如何正确地做这个?
I currently have a dropdown inside an ascx control. I need to "find" it from within the code behind on another ascx that is on the same page. It's value is used as a param to an ObjectDataSource on ascx #2. I am currently using this ugly piece of code. It works but I realize if the conrtol order were to change or various other things, it wouldn't be where I am expecting. Does anyone have any advice how I should properly be doing this?
if(Page is ClaimBase)
{
var p = Page as ClaimBase;
var controls = p.Controls[0].Controls[3].Controls[2].Controls[7].Controls[0];
var ddl = controls.FindControl("ddCovCert") as DropDownList;
}
感谢和新年快乐!
〜CK在圣地亚哥
Thanks and Happy New Year!! ~ck in San Diego
推荐答案
一般来说,我实施FindInPage,或当你有很多的控制发现的事,在这里你只想通过它控制递归的FindControl功能,它会递归下降控件树。
Generally I implement a "FindInPage" or recursive FindControl function when you have lots of control finding to do, where you would just pass it a control and it would recursively descend the control tree.
如果它只是一个一次性的东西,考虑露出你的API中需要这样你就可以直接对其进行访问控制。
If it's just a one-off thing, consider exposing the control you need in your API so you can access it directly.
public static Control DeepFindControl(Control c, string id)
{
if (c.ID == id)
{
return c;
}
if (c.HasControls)
{
Control temp;
foreach (var subcontrol in c.Controls)
{
temp = DeepFindControl(subcontrol, id);
if (temp != null)
{
return temp;
}
}
}
return null;
}
这篇关于ASP.NET有没有更好的办法找到其他的控制范围内的控制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!