如何在 Gridview 中获取第一行和最后一行?

How to get first and last row in Gridview?

我有一个 gridview 在页面加载时绑定数据:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack) 
    { 
        BindCustomerData(); 
    }
}

我想根据条件显示不同的按钮。为简单起见

如果它是第一个 gridview 行然后显示 "First Record"

如果它是 gridview 的最后一行则显示 "Last Record"

任何其他行"Middle Record"

所有按钮在标记上都以 Visible = False 开头。

在我的 RowDataBound 活动中我有

protected void gvCusts_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
    int lastIndex = gvCusts.Rows.Count -1;

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Button buttonFirst = (Button)e.Row.FindControl("buttonFirst");
        Button buttonMiddle = (Button)e.Row.FindControl("buttonMiddle");
        Button buttonLast = (Button)e.Row.FindControl("buttonLast");

        // Customer Records found
        if (c.Id > 0)
        {
            if (e.Row.RowIndex == 0)
            {
                // First row so display first button only
                buttonFirst.Visible = true;
            }
            else if (e.Row.RowIndex >= 1 && e.Row.RowIndex <= lastIndex)
            {
                // Not the first row and not the last row so display the middle button only
                buttonMiddle.Visible = true;
            }
            else if (e.Row.RowIndex == lastIndex)
            {
                // Last row, so display the last button only.
                buttonLast.Visible = true;
            }
        }
    }
}

问题是我找不到正确的方法来获取中间行和最后一行,并且按钮显示在错误的阶段。 然后我编写了 int lastIndex = gvCusts.Rows.Count -1; 代码行 static,但仍然没有得到正确的结果。

我已经阅读了很多文章,所以显然我在某处遗漏了一些东西但不确定是什么?

  1. 在 class 中声明一个静态变量 rowCount。
int rowCount=0;
  1. 在您的 BindCustomerData() 方法中,将行数传递给 rowCount 变量。
rowCount= YourDataTable.Rows.Count-1;
  1. 现在,从 rowCount 变量获取第一个和最后一个索引。
protected void gvCusts_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
    int lastIndex = rowCount;//rowCount has the last index

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Button buttonFirst = (Button)e.Row.FindControl("buttonFirst");
        Button buttonMiddle = (Button)e.Row.FindControl("buttonMiddle");
        Button buttonLast = (Button)e.Row.FindControl("buttonLast");

        // Customer Records found
        if (c.Id > 0)
        {
            if (e.Row.RowIndex == 0)
            {
                // First row so display first button only
                buttonFirst.Visible = true;
            }
            else if (e.Row.RowIndex >= 1 && e.Row.RowIndex < rowCount)
            {
                // Not the first row and not the last row so display the middle button only
                buttonMiddle.Visible = true;
            }
            else if (e.Row.RowIndex == rowCount)
            {
                // Last row, so display the last button only.
                buttonLast.Visible = true;
            }
        }
    }
}