如何在GridView中获取首末行并按行显示对应按钮?
解决GridView RowDataBound中无法正确识别首/中/末行的问题
我一眼就看出问题出在哪了——你在RowDataBound事件里用gvCusts.Rows.Count -1来获取最后一行索引是错误的。这是因为RowDataBound是在每一行绑定的时候触发的,此时GridView的Rows集合还在逐步构建中,每绑定一行,Rows.Count就加1。比如绑定第一行时,Rows.Count是1,lastIndex是0;绑定第二行时,Rows.Count是2,lastIndex是1,这显然不是最终的总行数,自然没法正确判断末行和中间行。
正确的解决步骤:
1. 先保存数据源的总行数
在绑定数据前,先获取数据源的总行数并保存,这样在RowDataBound里就能拿到最终的总行数了。
首先在你的页面类里定义一个私有变量:
private int _totalCustomerRows; // 用来存储数据源的总行数
然后修改BindCustomerData方法,在绑定前获取总行数:
protected void BindCustomerData() { // 假设你是从这里获取数据源,比如List<Customer>或者DataTable List<Customer> customerList = GetYourCustomerData(); // 替换成你实际获取数据的方法 _totalCustomerRows = customerList.Count; // 保存总行数 gvCusts.DataSource = customerList; gvCusts.DataBind(); }
2. 修正RowDataBound里的判断逻辑
现在用保存的_totalCustomerRows来计算最后一行索引,同时还要注意你代码里漏掉的获取当前行绑定的数据对象的步骤(c.Id那里如果没获取DataItem会报错):
protected void gvCusts_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { // 先获取当前行绑定的Customer对象,否则c.Id会报错 Customer c = (Customer)e.Row.DataItem; Button buttonFirst = (Button)e.Row.FindControl("buttonFirst"); Button buttonMiddle = (Button)e.Row.FindControl("buttonMiddle"); Button buttonLast = (Button)e.Row.FindControl("buttonLast"); if (c.Id > 0) { int lastIndex = _totalCustomerRows - 1; // 用数据源的总行数计算末行索引 if (e.Row.RowIndex == 0) { // 首行:只显示First按钮 buttonFirst.Visible = true; } else if (e.Row.RowIndex == lastIndex) { // 末行:只显示Last按钮 buttonLast.Visible = true; } else { // 中间行:只显示Middle按钮 buttonMiddle.Visible = true; } } } }
额外说明:
- 如果你的数据源是DataTable,那
_totalCustomerRows = dt.Rows.Count;就可以了,逻辑是一样的。 - 原来的
else if (e.Row.RowIndex >=1 && e.Row.RowIndex <= lastIndex)完全没必要,因为排除了首行和末行,剩下的自然就是中间行,直接用else更简洁。
这样修改后,就能准确识别首行、中间行和末行,按钮显示就符合预期了。
内容的提问来源于stack exchange,提问作者Computer
相关产品推荐
相关产品推荐

