You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET C#中GridView过滤后编辑行RowIndex获取错误求助

解决GridView过滤后编辑获取错误RowIndex的问题

核心问题原因

过滤后GridView的行索引基于当前显示的数据集,若代码错误依赖原始全量数据的索引,或绑定数据源时未保持一致性,就会出现索引不匹配的情况。以下是直接可行的解决方案:


1. 完全依赖DataKeys获取主键,放弃RowIndex关联原始数据

既然已将srno设为GridView的DataKey,直接通过事件参数的RowIndex获取对应行的DataKey值即可,该值与当前显示的过滤后数据完全对应,不受原始数据索引影响。

OnRowEditing 示例代码:

protected void GridView_RowEditing(object sender, GridViewEditEventArgs e)
{
    // 获取当前编辑行的srno主键
    int targetSrno = Convert.ToInt32(GridView.DataKeys[e.NewEditIndex].Value);
    
    // 设置编辑索引
    GridView.EditIndex = e.NewEditIndex;
    // 重新绑定过滤后的数据源(必须使用当前搜索条件的数据集)
    BindFilteredData();
}

OnRowUpdating 示例代码:

protected void GridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    // 获取当前更新行的srno主键
    int targetSrno = Convert.ToInt32(GridView.DataKeys[e.RowIndex].Value);
    
    // 获取编辑控件的值(示例:发票编号输入框)
    TextBox txtInvoiceNo = (TextBox)GridView.Rows[e.RowIndex].FindControl("txtInvoiceNo");
    string updatedInvoiceNo = txtInvoiceNo.Text.Trim();
    
    // 执行数据库更新:用srno作为WHERE条件,而非原始行索引
    UpdateInvoiceData(targetSrno, updatedInvoiceNo);
    
    // 退出编辑状态
    GridView.EditIndex = -1;
    // 重新绑定过滤后的数据
    BindFilteredData();
}

2. 统一数据源绑定逻辑

创建通用绑定方法BindFilteredData,无论首次加载、搜索过滤还是编辑后回发,都调用该方法获取并绑定当前条件下的过滤数据,确保GridView的DataKeys与显示行完全同步:

private void BindFilteredData()
{
    string searchInvoiceNo = txtSearchInvoice.Text.Trim();
    // 构建参数化查询,避免SQL注入
    string sqlQuery = "SELECT srno, InvoiceNo, [其他字段] FROM YourTable WHERE 1=1";
    List<SqlParameter> parameters = new List<SqlParameter>();
    
    if (!string.IsNullOrEmpty(searchInvoiceNo))
    {
        sqlQuery += " AND InvoiceNo = @InvoiceNo";
        parameters.Add(new SqlParameter("@InvoiceNo", searchInvoiceNo));
    }
    
    // 执行查询获取DataTable(替换为你的数据库操作逻辑)
    DataTable filteredData = ExecuteQuery(sqlQuery, parameters.ToArray());
    
    GridView.DataSource = filteredData;
    GridView.DataBind();
}

3. 修正Page_Load的回发逻辑

确保仅在首次加载(!IsPostBack)时执行初始绑定,回发时不重新绑定全量数据,避免覆盖过滤后的状态:

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

内容的提问来源于stack exchange,提问作者sush007

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 00:32:38