DialogResult并在按钮单击时显示消息

时间:2013-10-18 09:05:46

标签: c# .net winforms

我有两种形式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();
  }

显示消息仅在取消按钮上显示,而不是在确定时显示。我做错了什么?

2 个答案:

答案 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;
    }