You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在DevExpress GridControl中获取选中行及按钮所在行索引?

如何在DevExpress GridControl按钮点击事件中获取行索引及选中行索引

一、获取删除按钮所在的行索引

在你的delete_button_ButtonClick事件里,我们可以通过以下步骤准确拿到按钮所在的行:

  1. 先把事件参数里的sender转换成ButtonEdit控件(毕竟你的红色X按钮是ButtonEdit类型的);
  2. 找到按钮所属的GridView
  3. 通过GridView.CalcHitInfo方法结合鼠标位置,计算出点击位置对应的行信息。

示例代码如下:

private void delete_button_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
{
    // 将sender转为ButtonEdit,避免空引用
    var deleteBtn = sender as DevExpress.XtraEditors.ButtonEdit;
    if (deleteBtn == null) return;

    // 获取当前GridControl对应的GridView(假设你的GridControl命名为gridControl1)
    var gridView = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
    if (gridView == null) return;

    // 计算点击位置的HitInfo,拿到行信息
    var mousePos = deleteBtn.PointToClient(Control.MousePosition);
    var hitInfo = gridView.CalcHitInfo(mousePos);

    if (hitInfo.InRow)
    {
        int rowHandle = hitInfo.RowHandle; // 这是GridView内部的行索引(行句柄)
        // 如果需要对应数据源里的真实索引,用下面的方法转换
        int dataSourceIndex = gridView.GetDataSourceRowIndex(rowHandle);
        
        // 这里就可以用行索引做操作了,比如删除该行
        // gridView.DeleteRow(rowHandle);
    }
}

另外还有个更简洁的方式:点击按钮时该行通常会成为聚焦行,所以也可以直接用gridView.FocusedRowHandle获取,但这种方式不如CalcHitInfo可靠(比如用户快速连续点击时可能出现偏差)。

二、获取GridControl中的选中行索引

分两种场景处理:

1. 单行选中模式

如果你的GridView是默认的单行选中模式,直接用FocusedRowHandle就能拿到选中行的索引:

var gridView = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
if (gridView != null)
{
    int selectedRowHandle = gridView.FocusedRowHandle;
    // 转换为数据源中的真实索引
    int dataSourceIndex = gridView.GetDataSourceRowIndex(selectedRowHandle);
}

2. 多行选中模式

如果开启了多行选中(设置gridView.OptionsSelection.MultiSelect = true),用GetSelectedRows()方法获取所有选中行的句柄数组:

var gridView = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
if (gridView != null)
{
    int[] selectedRowHandles = gridView.GetSelectedRows();
    foreach (int rowHandle in selectedRowHandles)
    {
        if (rowHandle >= 0) // 排除分组行等无效行(分组行行句柄为负数)
        {
            int dataSourceIndex = gridView.GetDataSourceRowIndex(rowHandle);
            // 对每一行做业务处理
        }
    }
}

注意:RowHandle是GridView内部的行索引,可能包含分组行(负数),使用时最好加rowHandle >= 0的判断确保是数据行;如果需要和数据源中的索引对应,一定要用GetDataSourceRowIndex(rowHandle)做转换。

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

火山引擎 最新活动