如何在DevExpress GridView中获取双击行的值及相关问题
DevExpress GridView 问题解决方案
一、修复 CS1061 错误(CalcHitInfo 找不到)
该错误源于缺少必要的命名空间引用或事件参数处理错误,按以下步骤解决:
- 添加必备 using 指令:
using DevExpress.XtraGrid.Views.Grid; using DevExpress.XtraGrid.Views.Grid.ViewInfo; using DevExpress.Utils;
- 修正双击事件代码:
原生 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); } }
- 确认程序集引用:确保项目已引用
DevExpress.XtraGrid.dll和DevExpress.Utils.dll。
二、处理行单元格点击事件
直接使用 GridView 自带的 RowCellClick 事件,无需手动判断点击位置:
- 绑定事件(可在设计器中操作或手动添加):
gridView2.RowCellClick += GridView2_RowCellClick;
- 实现事件处理逻辑:
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:通过构造函数传递整行实体对象
- 在
DetailForm中定义带参数的构造函数:
public class DetailForm : Form { // 假设行数据对应实体类为 Customer public Customer CurrentData { get; set; } public DetailForm(Customer data) { InitializeComponent(); CurrentData = data; // 绑定值到窗口控件,示例:txtName.Text = CurrentData.Name; } }
- 在双击事件中打开窗口并传参:
if (info.InRow || info.InRowCell) { Customer rowData = view.GetRow(info.RowHandle) as Customer; if (rowData != null) { DetailForm detailWin = new DetailForm(rowData); detailWin.ShowDialog(); } }
方式2:通过属性传递单个字段值
- 在
DetailForm中添加属性:
public string TargetId { get; set; }
- 在双击事件中赋值并打开窗口:
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
相关产品推荐
相关产品推荐

