I have a WinForm, and add a UserControl with a DataGridView. Now I want to do a doubleClick on the DataGridView and get the object data to my Form.
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.
CodePudding user response:
You can change the delegate to one you define or use the generic form of 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.
Below is an example using the Action delegate, with T being your Address type.
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}");
}