在页面上查找控件并获取文本

时间:2013-06-24 14:40:08

标签: c# asp.net

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

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);
}

3 个答案:

答案 0 :(得分:2)

FindControl方法不是递归的。尝试使用Linq样式更新的a former answer代码,并作为扩展方法:

    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;

        }
    }

答案 1 :(得分:1)

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

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

来自Control.FindControl的文档:

  

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

此外: 有关如何在不知道其直接容器时查找控件的信息,请参见如何:Access Server Controls by ID

答案 2 :(得分: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");