循环访问Web控件的问题

时间:2011-08-18 13:30:55

标签: c# asp.net

我有一个网页,我在Page_Load事件期间动态创建控件(这样做是因为我不知道在会话处于活动状态并且某些变量可访问之前我需要多少控件)< / p>

我需要能够循环浏览这些控件,以便在处理按钮单击时找到Checkbox。循环使用Form.Controls似乎不够。我认为Request.Form可能有效,但它似乎无法在我的C#块中访问?

Request.Form的代码应该是什么样的? OR

之前是否有人使用动态创建的控件执行此操作?

感谢任何见解。

5 个答案:

答案 0 :(得分:0)

MSDN的简化示例:

var myControl = FindControl("NameOfControl");
if(myControl != null)
{
   //do something
}
else
{
   //control not found
}

希望这有帮助! ;)

答案 1 :(得分:0)

您的控件可以通过其直接父级的Controls集合访问。除非您像Page.Form.Controls.Add (myControl);一样添加它们,否则您将无法在Page.Form.Conttrols中找到它。如果您将它们添加到占位符,则必须在thePlaceHolder.Controls中找到它们。

LinkButton myDynamicLinkButton = new myDynamicLinkButton ();
myDynamicLinkButton.ID = "lnkButton";

myPlaceHolder.Controls.Add (myDynamicLinkButton);

//........

LinkButton otherReferenceToMyLinkButton = myPlaceHolder.FindControl ("lnkButton");

正如@David在评论中所说,你应该考虑改用Repeater。它可能会大大简化你的情况。

答案 2 :(得分:0)

由于控件可能嵌套在其他控件中,因此需要递归搜索。您可以使用此方法查找控件:

 public Control FindControlRecursive(Control root, string id)
 {
     if (root.ID == id)
     {
         return root;
     }

     foreach (Control c in root.Controls)
     {
         Control t = FindControlRecursive(c, id);
         if (t != null)
         {
             return t;
         }
     }

     return null;
 }

你可以这样实现它:

CheckBox check = FindControlRecursive(Page.Form, "CheckBox1");   

答案 3 :(得分:0)

您应该可以在aspx.cs代码中的任何位置访问Request["xyz"]。您可以按上述方法查找控件并读取其值,也可以使用Control.UniqueID属性直接从Request执行此操作。例如,如果它是转发器内的复选框,则UniqueID看起来像dtgData $ ctl02 $ txtAmount

答案 4 :(得分:0)

感谢有识之士。我有点参与讨论并与它一起运行,并找到了最适合我的解决方案。

foreach(String chk in Request.Form) 
{
    if (chk.Contains("chkRemove")) 
    {
        int idxFormat = chk.LastIndexOf("chkRemove"); 
        objectname = chk.Substring(idxFormat);
    }
}

原来我真正需要的只是名字。该字符串在末尾包含一个数字,用于确定可数据项的位置。谢谢你的建议!