我有两种形式Form1和Form2。
在Form1中我调用Form2,我想拦截用户按钮单击选项。如果Form2上的用户单击“确定”或“取消”按钮,则尝试
var editForm = new Form2();
editForm.ShowDialog();
if (editForm.DialogResult == DialogResult.OK)
{
MessageBox.Show("ok btn is pressed!");
editForm.Dispose();
}
else
{
MessageBox.Show("cancel btn is pressed!");
editForm.Dispose();
}
Form2上的我有点击事件
private void BtnOk_Click(object sender, EventArgs e)
{
_Repository.Create(mydata);
}
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
}
显示消息仅在取消按钮上显示,而不是在确定时显示。我做错了什么?
答案 0 :(得分:4)
关闭前设置dialog result
。
private void BtnOk_Click(object sender, EventArgs e)
{
_Repository.Create(mydata);
DialogResult = DialogResult.Ok;
Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
}
答案 1 :(得分:1)
在你的Form1上:
using (Form2 editForm = new Form2())
{
editForm.ShowDialog();
if (editForm.DialogResult == DialogResult.OK)
{
MessageBox.Show("ok btn is pressed!");
editForm.Dispose();
}
else
{
MessageBox.Show("cancel btn is pressed!");
editForm.Dispose();
}
}
在Form2上:
private void BtnOk_Click(object sender, EventArgs e)
{
_Repository.Create(mydata);
this.DialogResult = DialogResult.OK;
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}