[英]FindControl not working on GridView when inserting bound columns
我有幾個項目模板的gridview。 第一個包含一個復選框,其余包含一個文本框。
然后,我動態添加了一些綁定控件,如下所示:
BoundField bdfPrivName = new BoundField();
clsUtilities.SetBoundFieldCenter(ref bdfPrivName, "PrivName", "Priv Name");
BoundField bdfDescription = new BoundField();
clsUtilities.SetBoundFieldLeft(ref bdfDescription, "PrivDesc", "Description");
BoundField bdfLive = new BoundField();
clsUtilities.SetBoundFieldCenter(ref bdfLive, "Live","Active?");
grdExisting.Columns.Add(bdfPrivName);
grdExisting.Columns.Add(bdfDescription);
grdExisting.Columns.Add(bdfLive);
然后,我使用FindControl()定位復選框和文本框,並根據結果執行我的邏輯
foreach (GridViewRow gvr in grdMissing.Rows)
{
mckbAny = (CheckBox)gvr.FindControl("ckbAdd");
mtxtApplyDate = (TextBox)gvr.FindControl("txtAddApplyDate");
mtxtDateToAdd = (TextBox)gvr.FindControl("txtAddDateToAdd");
mtxtDateToRemove = (TextBox)gvr.FindControl("txtAddDateToRemove");
}
等等
這一切都很好。 然后,我得到一個請求,將綁定的字段放在復選框之后和文本框之前,作為第二,第三和第四列。 我發現,通過如下方式將“添加到插入”更改很容易做到:
grdExisting.Columns.Insert(1, bdfPrivName);
grdExisting.Columns.Insert(2, bdfDescription);
grdExisting.Columns.Insert(3, bdfLive);
頁面看起來不錯,但是FindControl()都無法正常工作。
請提出解決方案或解決方法。
提前致謝。
聽起來您遇到了此錯誤:
將BoundField插入GridView時,似乎不會存儲(或恢復)ViewState。 因此,當您執行FindControl時,它不存在。
您可以像以前一樣嘗試添加它們,並找到某種方式重新排列列(我認為這是可能的)。
我不確定它以前如何為您工作,因為控件不屬於行-它們位於單元格內。 無論如何,問題在於FindControl不是遞歸的,它不會搜索整個控件樹-僅搜索在其上運行的控件的直接子級。 您需要實現自己的遞歸findcontrol,例如:
public static Control FindControlRecursive(Control Root, string Id)
{
if (Root.ID == Id)
return Root;
foreach (Control c in Root.Controls)
{
Control fc = FindControlRecursive(c, Id);
if (fc != null)
return fc;
}
return null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.