[英]Problem looping through web controls
我有一個網頁,可以在Page_Load
事件期間動態創建控件(這樣做是因為在會話處於活動狀態並且某些變量可以訪問之前,我不知道需要多少控件)
處理按鈕單擊后,我需要能夠遍歷這些控件以找到“復選框”。 遍歷Form.Controls似乎還不夠。 我認為Request.Form
可能可以工作,但在我的C#塊中似乎無法訪問?
Request.Form
代碼應該是什么樣? 要么
以前有人用動態創建的控件來做到這一點嗎?
任何見解均表示贊賞。
來自MSDN的簡化示例:
var myControl = FindControl("NameOfControl");
if(myControl != null)
{
//do something
}
else
{
//control not found
}
希望這可以幫助! ;)
您的控件可以通過其直接父級的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在他的評論中所說,您可能應該考慮使用中繼器。 這可能會大大簡化您的案件。
由於這些控件可能嵌套在其他控件中,因此您需要遞歸搜索。 您可以使用此方法找到控件:
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");
您應該可以在aspx.cs代碼中的任何位置訪問Request["xyz"]
。 您可以如上所述找到控件並讀取其值,也可以使用Control.UniqueID
屬性直接從Request中讀取控件的值。 例如,如果它是轉發器中的一個復選框,則UniqueID
類似於dtgData $ ctl02 $ txtAmount
多謝有識之士。 我有點討論並進行討論,發現最適合我的解決方案。
foreach(String chk in Request.Form)
{
if (chk.Contains("chkRemove"))
{
int idxFormat = chk.LastIndexOf("chkRemove");
objectname = chk.Substring(idxFormat);
}
}
原來,我真正需要的只是名字。 該字符串的末尾包含一個數字,該數字是確定數據表項位置所需的。 謝謝你的建議!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.