【问题标题】:Unable to find control in gridview在gridview中找不到控件
【发布时间】:2012-06-22 21:26:34
【问题描述】:

我想在gridview 中找到控件(超链接)。根据控件的值,我想启用或禁用超链接。 我试过这样。但我总是变得空虚。

protected void gridResult_RowDataBound(object sender, GridViewRowEventArgs e) { 
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        HyperLink  status = e.Row.FindControl("id") as HyperLink;
        if ( status != null && status.Text == "AAAA" ) {
            status.Enabled = false; 
        }
    }
}

请帮忙。

【问题讨论】:

  • FindControl() 不是递归的,所以如果超链接不是Row 的直接子级,则不会找到它。您可能需要实现自己的递归版本才能获得所需的功能。有关更多信息,请参阅msdn.microsoft.com/en-us/library/486wc64h.aspx
  • 你好,你可以发送你的代码aspx
  • 如 Aghilas 所述,如果以下答案未能解决您的问题,则需要您的 GridView ASPX 代码。

标签: c# asp.net gridview findcontrol templatefield


【解决方案1】:

您的“id”值非常可疑。我的钱是因为您提供了错误的控件名称:FindControl("id!!!!!!!")

我希望看到类似的东西:

HyperLink  status = e.Row.FindControl("hlStatus") as HyperLink;

如果您确实提供了正确的控件名称 (yuck),那么可能是您的超链接控件嵌套得太深,在这种情况下,您需要“爬取”控件层次结构来寻找它。

【讨论】:

    【解决方案2】:

    @dlev 是绝对正确的,控件通常是嵌套的,因此您需要创建自己的各种函数来查找您要查找的内容,您可以将此函数传递给您的控件集合 (e.Row.Controls()) 和您的身份证

        private HyperLink FindControl(ControlCollection page, string myId)
        {
            foreach (Control c in page)
            {
                if ((HyperLink)c.ID == myId)
                {
                    return (HyperLink)c;
                }
                if (c.HasControls())
                {
                    FindControl(c.Controls, myId);
                }
            }
            return null; //may need to exclude this line
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多