使用DialogResult
和Form2
刷新Form3
项目Form1
:
// on Form1
using(var form2 = new Form2(item))
{
if (form2.ShowDialog() == DialogResult.OK)
{
// update items
}
}
根据用户的操作,Form2
将其DialogResult
属性设置为等。例如,当用户删除项目时,将结果设置为:DialogResult.OK
DialogResult.Cancel
DialogResult.OK
// on Form2
private void btnDelete_Click(object sender, EventArgs e)
{
// delete item from db
DialogResult = DialogResult.OK;
}
更新 - 如果你想保持打开两个表单,那么你不能显示Form2
为对话框,上面的代码对你不起作用。您需要声明以下事件Form2
:
// on Form2
public event EventHandler<ItemDeletedEventArgs> ItemDeleted;
public Form2(List<Item> items)
{
...
}
private void btnDelete_Click(object sender, EventArgs e)
{
// delete item from db
OnItemDeleted(itemId)
}
protected void OnItemDeleted(int itemId)
{
if (ItemDeleted == null)
return;
ItemDeleted(this, new ItemDeletedEventArgs(itemId));
}
订阅此活动Form1
:
private void form2_ItemDeleted(object sender, ItemDeletedEventArgs e)
{
int itemId = e.ItemId;
// update items
}
ItemDeletedEventArgs
继承自的自定义类在哪里EventArgs
:
public class ItemDeletedEventArgs : EventArgs
{
public ItemDeletedEventArgs(int itemId);
{
ItemId = itemId;
}
public int ItemId { get; private set; }
}
如果您不想遵循所有这些 Microsoft 事件类型指南EventHandler
、类型参数EventArgs
,那么您可以使用简单类型事件Action<int>
:
public event Action<int> ItemDeleted;
并以这种方式提出:
if (ItemDeleted != null)
ItemDelted(itemId);