[英]How to get first and last row in Gridview?
我有一個gridview
,它在頁面加載時綁定數據:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindCustomerData();
}
}
我想根據條件顯示不同的按鈕。 為簡單起見
如果它是第一個 gridview 行,則顯示“第一條記錄”
如果它是最后一個 gridview 行,則顯示“最后一條記錄”
任何其他行“中間記錄”
所有按鈕在標記上都以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
,仍然沒有得到正確的結果。
我已經閱讀了很多文章,很明顯我在某處遺漏了一些東西,但不確定是什么?
int rowCount=0;
rowCount= YourDataTable.Rows.Count-1;
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;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.