为什么 rowdatabound 中的条件会失败?

Why condition in rowdatabound is getting failed?

我正在尝试显示一个 IsPublished 为 true 的按钮,它可以工作,但网格中的第一行除外。为什么?试了这么久还是不行

protected void gvNITs_RowDataBound(object sender, GridViewRowEventArgs e)
{
    try
    {
        //LinkButton lb = e.Row.FindControl("btnLinkDownload") as LinkButton;
        //if (lb != null)
        //    ScriptManager.GetCurrent(this).RegisterPostBackControl(lb);

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton Lbtn_change = (LinkButton)e.Row.FindControl("Lbtn_change");
            HiddenField hdnPublishNITDate = e.Row.FindControl("hdnPublishedNITdate") as HiddenField;
            DateTime? dtPublishedNITDate = string.IsNullOrEmpty(hdnPublishNITDate.Value) == true ? null : (DateTime?)hdnPublishNITDate.Value.ToDate();
            HiddenField hdnIsPublishedNIT = e.Row.FindControl("hdnIsPublishedNITs") as HiddenField;
            bool IsPublished = hdnIsPublishedNIT.Value.ToBool();

            GridView gv = (GridView)sender;

            foreach (GridViewRow gvr in gv.Rows)
            {
                if (IsPublished == true)
                {
                    Lbtn_change.Visible = true;
                }
            }
        }
    }
}

它不起作用,因为你有一个嵌套循环。 RowDataBound 事件在将行添加到 GridView 时触发。但是在 RowDataBound 事件中,您循环了 GridView foreach (GridViewRow gvr in gv.Rows)

中的所有行

如果你检查gv.Rows.Count,你会发现它在第一行是0,因为它还没有被添加到GridView。

但是您不需要那个循环,因为您已经可以访问 Lbtn_change。所以在没有循环的情况下设置可见属性。