FindControl not working on GridView when inserting bound columns
I have a gridview with several ItemTemplates. The first contains a checkbox the rest contain textboxes.
I then added dynamically some bound controls like this:
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);
I then use FindControl() to locate the checkbox and textboxes and perform my logic based the result
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");
}
etc.
This all worked fine. I then got a request to put the bound fields as the second, third and fourth columns, after the check box and before the textboxes. I found that this was easy to do by changing the Add’s to Inserts as follows:
grdExisting.Columns.Insert(1, bdfPrivName);
grdExisting.Columns.Insert(2, bdfDescription);
开发者_StackOverflow中文版grdExisting.Columns.Insert(3, bdfLive);
It looked fine of the page, but the FindControl(), all of them fail to work.
Please suggest a solution or a workaround.
Thanks in advance.
It sounds like you have come across this bug:
https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=104994&wa=wsignin1.0
It appears ViewState is not stored (or restored) when a BoundField is inserted into a GridView. So when you do FindControl it doesn't exist.
You could try adding them as you did before and finding some way of re-arranging the columns (I think this is possible).
I am not sure how it was working for you before, as controls don't belong in row - they are inside cells. Anyways, the issue is that FindControl is not recursive, it will not search entire control tree - only immediate children of the control you run it on. You need to implement your own recursive findcontrol, for example like so:
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;
}
精彩评论