-2

我正在尝试获取标签的文本并将其分配给字符串,但它似乎无法找到控件。请注意,这是在我的页面后面的代码中完成的(后面代码的自动生成功能不正常,所以我必须手动找到它)。

public void ObtainDate()
{
    var controlList = ProductPromotion.Controls;

    foreach (Control control in controlList)
    {
        if (control is TableRow)
        {
            var newControl = control.FindControl("StartDate");
            if (newControl != null)
            {
                Label startControl = newControl as Label;
                startDate = startControl.Text;
            }
        }
    }

    Fabric.SettingsProvider.WriteSetting<string>(startDate, startSetting);
}
4

3 回答 3

2

FindControl方法不是递归的。尝试以前答案的代码,该代码已以 Linq 样式更新,并作为扩展方法:

    public static IEnumerable<TControl> FindDescendants<TControl>(this Control parent) 
        where TControl : Control
    {
        if (parent == null) throw new ArgumentNullException("control");

        if (parent.HasControls())
        {
            foreach (Control childControl in parent.Controls)
            {
                var candidate = childControl as TControl;
                if (candidate != null) yield return candidate;

                foreach (var nextLevel in FindDescendants<TControl>(childControl))
                {
                    yield return nextLevel;
                }
            }
        }
    }

用法:

    if (control is TableRow)
    {
        var newControl = control.FindDescendants<Label>()
            .Where(ctl=>ctl.ID =="StartDate")
            .FirstOrDefault();

        if (newControl != null)
        {

            startDate = newControl.Text;

        }
    }
于 2013-06-24T14:43:24.070 回答
1

我猜测“StartDate”控件嵌套在另一个控件中,所以.FindControl没有看到它。

http://msdn.microsoft.com/en-us/library/486wc64h.aspx

从文档中Control.FindControl

只有当控件直接包含在指定容器中时,此方法才会找到控件;也就是说,该方法不会在控件内的控件层次结构中进行搜索。

进一步:有关如何在不知道其直接容器时查找控件的信息,请参阅如何:按 ID 访问服务器控件

于 2013-06-24T14:48:51.813 回答
0

我怀疑控件是嵌套的,而FindControl看不到它。在这种情况下,您需要在页面控件集合中递归检查它,例如

private Control FindMyControl(Type type, ControlCollection c, string id)
{
     Control result = null;
     foreach (Control ctrl in c)
     {
         //checks top level of current control collection, if found breaks out and returns result
         if (ctrl.GetType() == type && ctrl.ID == id)
         {
             result = ctrl;
             break;
         }
         else//not found, search children of the current control until it is - if it's not found we will eventually return null
         {
             result = FindMyControl(type, ctrl.Controls, id);

             if (result != null)
             {
                 break;
             }
         }
     }

     return result;
 }

示例用法:-

Literal myLiteral = (Literal)FindMyControl(typeof(Literal), this.Controls, "control id here");
于 2013-06-24T14:53:13.860 回答