简体   繁体   English

使用委托事件处理程序从 UserControl 获取数据到 Form

[英]Using delegate event handler to get data from UserControl to Form

I have a WinForm, and add a UserControl with a DataGridView.我有一个 WinForm,并添加了一个带有 DataGridView 的 UserControl。 Now I want to do a doubleClick on the DataGridView and get the object data to my Form.现在我想双击 DataGridView 并将 object 数据添加到我的表单中。

In my UserControl:在我的用户控件中:

 public event DataGridViewCellEventHandler dg_CellDoubleClickEvent;

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)
                    {
                       // how can I pass my Address object??
                        dgAngebote_CellDoubleClickEvent?.Invoke(this.dgAngebote, e);
                        
                    }
                    
                }
                finally { Cursor.Current = Cursors.Default; }
            }
        }

In my Form:在我的表格中:

 private void FormAddress_Load(object sender, EventArgs e)
        {
            uc.dg_CellDoubleClickEvent += new DataGridViewCellEventHandler(myEvent);
        }
        private void myEvent(object sender, DataGridViewCellEventArgs e)
        {
            MessageBox.Show("test");
        }

My MessageBox is shown.显示我的消息框。 This is ok, but I want to geht my Address to show.没关系,但我想显示我的地址。 Is this the right way of doing that?这是这样做的正确方法吗? How?如何?

Kind regards.亲切的问候。

You can change the delegate to one you define or use the generic form of System.Action.您可以将委托更改为您定义的委托或使用 System.Action 的通用形式。 There is also the option to use EventHandler and define your own event args class that you can add properties and logic to.还可以选择使用 EventHandler 并定义您自己的事件参数 class,您可以向其添加属性和逻辑。

Below is an example using the Action delegate, with T being your Address type.下面是一个使用 Action 委托的示例,其中 T 是您的地址类型。

public event Action<Address> OnAddressSelected;

...

Address address = dg.Rows[e.RowIndex].DataBoundItem as Address;

if (address != null)
{
    OnAddressSelected?.Invoke(address);
}

And in the form并在表格中

private void FormAddress_Load(object sender, EventArgs e)
{
    uc.OnAddressSelected += OnAddressSelected;
}
private void OnAddressSelected(Address address)
{
    MessageBox.Show($"Address: {address}");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM