【问题标题】:FindControl not working on GridView when inserting bound columns插入绑定列时,FindControl 在 GridView 上不起作用
【发布时间】:2010-11-08 21:10:04
【问题描述】:

我有一个带有多个 ItemTemplate 的 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");
}

等等

这一切都很好。然后我收到一个请求,将绑定字段作为第二、第三和第四列,在复选框之后和文本框之前。我发现这很容易通过将 Add's 更改为 Inserts 来实现,如下所示:

grdExisting.Columns.Insert(1, bdfPrivName);
grdExisting.Columns.Insert(2, bdfDescription);
grdExisting.Columns.Insert(3, bdfLive);

页面看起来不错,但是 FindControl() 都无法正常工作。

请提出解决方案或解决方法。

提前致谢。

【问题讨论】:

    标签: c# asp.net gridview findcontrol


    【解决方案1】:

    听起来你遇到了这个错误:

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

    在将 BoundField 插入 GridView 时,似乎未存储(或恢复)ViewState。因此,当您执行 FindControl 时,它不存在。

    您可以尝试像以前一样添加它们并找到重新排列列的方法(我认为这是可能的)。

    【讨论】:

    【解决方案2】:

    我不确定它以前是如何为您工作的,因为控件不属于行 - 它们位于单元格内。无论如何,问题在于 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-02
      • 2015-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多