当前位置: 首页 > 编程语言 > C#

在webform中查找控件分享

时间:2023-04-10 13:38:55 C#

C#学习教程:在Webform中查找控件我知道两种访问控件的方法:TextBoxtxt=(TextBox)Page.Controls[0].Controls[3].Controls[48].Controls[6]通过编写搜索所有控件的递归函数。还有其他更简单的方法,因为Page.FindControl在这种情况下不起作用。我问的原因是我觉得Page对象或ContentPanel对象应该有一种方法来查找子控件,但找不到类似的东西。问题是FindControl()不会迭代某些控件子项,例如模板化控件。如果您使用的控件存在于模板中,它将无法找到它。所以我们添加了以下扩展方法来处理这个问题。如果您不使用3.5或想避免使用扩展方法,则可以使用这些方法创建一个通用库。您现在可以编写代码来获取您想要的控件:varbutton=Page.GetControl("MyButton")asButton;扩展方法为您完成递归工作。希望这可以帮助!publicstaticIEnumerableFlatten(thisControlCollectioncontrols){Listlist=newList();controls.Traverse(c=>list.Add(c));返回列表;}publicstaticIEnumerableFlatten(thisControlCollectioncontrols,Funcpredicate){Listlist=newList();controls.Traverse(c=>{if(predicate(c))list.Add(c);});返回列表;}publicstaticvoidTraverse(thisControlCollectioncontrols,Actionaction){foreach(Controlcontrolincontrols){action(control);如果(control.HasControls()){control.Controls.Traverse(action);}}}publicstaticControlGetControl(thisControlcontrol,stringid){returncontrol.Controls.Flatten(c=>c.ID==id).SingleOrDefault();}publicstaticIEnumerableGetControls(thisControlcontrol){returncontrol.Controls.Flatten();}我想将GetControls函数改为通用函数,如下所示:publicstaticTGetControl(thisControlcontrol,stringid)whereT:Control{varresult=control.Controls.Flatten(c=>(c.GetType().IsSubclassOf(typeof(T)))&&(c.ID==id)).SingleOrDefault();如果(结果==null)返回null;返回结果为T;然后,publicstaticControlGetControl(thisControlcontrol,stringid){returncontrol.GetControl(id);}这样,调用者就会调用类似:以上是C#学习教程:在webform中找到控件分享的所有内容,如果对大家有用需要进一步了解C#希望大家付费更多关注教程—varbutton=Page.GetControl("MyButton");