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

如何在DevExpress GridView中获取双击行的值及相关问题

DevExpress GridView 问题解决方案

一、修复 CS1061 错误(CalcHitInfo 找不到)

该错误源于缺少必要的命名空间引用或事件参数处理错误,按以下步骤解决:

  1. 添加必备 using 指令:
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.Utils;
  1. 修正双击事件代码:
    原生 DoubleClick 事件参数为 EventArgs,需通过 DXMouseEventArgs.GetMouseArgs(e) 获取正确的鼠标事件参数,同时完善空值判断:
private void gridView2_DoubleClick_1(object sender, EventArgs e)
{
    try
    {
        GridView view = sender as GridView;
        if (view == null) return;
        
        DXMouseEventArgs ea = DXMouseEventArgs.GetMouseArgs(e);
        GridHitInfo info = view.CalcHitInfo(ea.Location);
        
        if (info.InRow || info.InRowCell)
        {
            // 替换为你的目标列名,获取该行对应列的值
            object rowValue = view.GetRowCellValue(info.RowHandle, "TargetColumnName");
            string colCaption = info.Column == null ? "N/A" : info.Column.GetCaption();
            MessageBox.Show(string.Format("双击行:{0},列:{1},值:{2}", info.RowHandle, colCaption, rowValue));
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("操作错误:" + ex.Message);
    }
}
  1. 确认程序集引用:确保项目已引用 DevExpress.XtraGrid.dll 和 DevExpress.Utils.dll。

二、处理行单元格点击事件

直接使用 GridView 自带的 RowCellClick 事件,无需手动判断点击位置:

  1. 绑定事件(可在设计器中操作或手动添加):
gridView2.RowCellClick += GridView2_RowCellClick;
  1. 实现事件处理逻辑:
private void GridView2_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
{
    object cellValue = gridView2.GetRowCellValue(e.RowHandle, e.Column);
    MessageBox.Show(string.Format("点击行:{0},列:{1},值:{2}", e.RowHandle, e.Column.GetCaption(), cellValue));
}

三、将行值传递到新窗口

以名为 DetailForm 的新窗口为例,提供两种常见传递方式:

方式1:通过构造函数传递整行实体对象

  1. 在 DetailForm 中定义带参数的构造函数:
public class DetailForm : Form
{
    // 假设行数据对应实体类为 Customer
    public Customer CurrentData { get; set; }

    public DetailForm(Customer data)
    {
        InitializeComponent();
        CurrentData = data;
        // 绑定值到窗口控件,示例:txtName.Text = CurrentData.Name;
    }
}
  1. 在双击事件中打开窗口并传参:
if (info.InRow || info.InRowCell)
{
    Customer rowData = view.GetRow(info.RowHandle) as Customer;
    if (rowData != null)
    {
        DetailForm detailWin = new DetailForm(rowData);
        detailWin.ShowDialog();
    }
}

方式2:通过属性传递单个字段值

  1. 在 DetailForm 中添加属性:
public string TargetId { get; set; }
  1. 在双击事件中赋值并打开窗口:
if (info.InRow || info.InRowCell)
{
    string targetId = view.GetRowCellValue(info.RowHandle, "IdColumn").ToString();
    DetailForm detailWin = new DetailForm();
    detailWin.TargetId = targetId;
    detailWin.ShowDialog();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 04:42:54