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

如何通过委托事件从UserControl向WinForm传递DataGridView选中的Address对象

问题分析与解决方案

当前实现的问题在于:你使用的DataGridViewCellEventHandler是标准委托,它的事件参数DataGridViewCellEventArgs仅包含行/列索引信息,无法携带自定义的Address对象,所以主窗体的事件处理方法拿不到目标数据。

修改步骤:

  1. 在UserControl中定义自定义委托和事件
    替换原有的标准事件,改成能传递Address对象的自定义事件:
// 定义自定义委托,参数包含触发源、单元格事件参数,以及要传递的Address对象
public delegate void DataGridViewRowDoubleClickWithAddressEventHandler(object sender, DataGridViewCellEventArgs e, Address address);

// 声明对应的自定义事件
public event DataGridViewRowDoubleClickWithAddressEventHandler dg_RowDoubleClickWithAddress;

private void dg_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex != -1)
    {
        try
        {
            Cursor.Current = Cursors.WaitCursor;
            Address a = dg.Rows[e.RowIndex].DataBoundItem as Address;
            if (a != null)
            {
                // 触发自定义事件,同时传递Address对象
                dg_RowDoubleClickWithAddress?.Invoke(this.dg, e, a);
            }
        } 
        finally 
        { 
            Cursor.Current = Cursors.Default; 
        }
    }
}
  1. 在主窗体中订阅自定义事件
    修改主窗体的事件订阅和处理方法,接收传递过来的Address对象:
private void FormAddress_Load(object sender, EventArgs e)
{
    // 订阅自定义事件
    uc.dg_RowDoubleClickWithAddress += MyRowDoubleClickWithAddressHandler;
}

private void MyRowDoubleClickWithAddressHandler(object sender, DataGridViewCellEventArgs e, Address address)
{
    // 这里可直接使用双击行对应的Address对象,示例展示属性内容
    MessageBox.Show($"地址:{address.Street},城市:{address.City}");
}

补充说明

如果不想定义全新委托,也可以用EventHandler<T>泛型委托,自定义一个包含Address的事件参数类,但上述方式更直接简洁,适配你的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 18:35:40