如何检查GridView是否包含某个按钮asp.net c#

时间:2015-09-29 06:27:13

标签: c# asp.net button gridview

您好我想知道如何检查网格视图中是否有任何reviewBtn可见,如果 ANY reviewBtn存在,btn_reviewAll将是可见的。

目前,以下代码仅在所有 reviewBtn可见时显示btn_reviewAll。请指教谢谢!

foreach (GridViewRow row in GridViewReview.Rows)
{
    Control reviewBtn = row.FindControl("ButtonReview") as Button;

    if (reviewBtn.Visible == true)
    {
       btn_reviewAll.Visible = true;
    }
    else
    {
       btn_reviewAll.Visible = false;
    }
}

2 个答案:

答案 0 :(得分:4)

像这样更改您的代码

foreach (GridViewRow row in GridViewReview.Rows)
{
    Control reviewBtn = row.FindControl("ButtonReview") as Button;

    if (reviewBtn.Visible == true)
    {
         btn_reviewAll.Visible = true;
         break;
    }
    else
    {
       btn_reviewAll.Visible = false;
    }
}

它的作用是当一个reviewBtn可见时,它会将btn_reviewAll设置为可见并打破foreach循环

答案 1 :(得分:1)

@Shreesha的回答是绝对正确的,你也可以使用LINQ这样的代码来做更少的代码: -

if (GridViewReview.Rows.OfType<GridViewRow>()
                  .Any(b => ((Button)b.FindControl("ButtonReview")).Visible))
      btn_reviewAll.Visible = true;
else
      btn_reviewAll.Visible = false;