2010-11-08 23 views
0

我有一個GridView和幾個ItemTemplates。第一個包含一個複選框,其餘包含文本框。當插入綁定列時,FindControl無法在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(),它們都無法正常工作。

請提出解決方案或解決方法。

在此先感謝。

回答

-1

我不確定它是如何爲你工作的,因爲控件不屬於行 - 它們在單元格內。無論如何,問題在於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; 
} 
0

這聽起來像你所遇到的這個錯誤:

https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=104994&wa=wsignin1.0

看來ViewState中沒有存儲(或恢復)當一個BoundField被插入到一個GridView中。所以當你做FindControl時它不存在。

你可以嘗試像以前那樣添加它們,並找到某種重新安排列的方式(我認爲這是可能的)。

+0

剛剛遇到這個自己,雖然該鏈接不工作了 - 我確實發現這個:http://connect.microsoft.com/VisualStudio/feedback/details/104994/templatefield-in-a-gridview-沒有擁有它的viewstate-restored-when-boundfields被插入,但沒有指出它何時將被修復或有其他解決方法可用。 – 2013-09-11 00:28:32

相關問題