我有一個 WinForm,并添加了一個帶有 DataGridView 的 UserControl。現在我想雙擊 DataGridView 并將物件資料添加到我的表單中。
在我的用戶控制元件中:
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; }
}
}
在我的表格中:
private void FormAddress_Load(object sender, EventArgs e)
{
uc.dg_CellDoubleClickEvent = new DataGridViewCellEventHandler(myEvent);
}
private void myEvent(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show("test");
}
顯示我的訊息框。沒關系,但我想顯示我的地址。這是這樣做的正確方法嗎?如何?
親切的問候。
uj5u.com熱心網友回復:
您可以將委托更改為您定義的委托或使用 System.Action 的通用形式。還可以選擇使用 EventHandler 并定義您自己的事件引數類,您可以向該類添加屬性和邏輯。
下面是一個使用 Action 委托的示例,其中 T 是您的地址型別。
public event Action<Address> OnAddressSelected;
...
Address address = dg.Rows[e.RowIndex].DataBoundItem as Address;
if (address != null)
{
OnAddressSelected?.Invoke(address);
}
并在表格中
private void FormAddress_Load(object sender, EventArgs e)
{
uc.OnAddressSelected = OnAddressSelected;
}
private void OnAddressSelected(Address address)
{
MessageBox.Show($"Address: {address}");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/537454.html
上一篇:如何使C#winform回應
