如何从表单显示对话框方法返回其他值?

时间:2014-05-21 13:13:32

标签: winforms showdialog dialogresult

我有一个winform,我称之为这个方法:

frmIntegrationConfig frm = new frmIntegrationConfig();
DialogResult res = frm.ShowDialog();

res始终返回为" Canceld"。 如何根据用户点击"保存"按钮o r刚关闭了关闭按钮的形式(" X")?

2 个答案:

答案 0 :(得分:1)

定义frmIntegrationConfig()窗口时,应将窗体上的“AcceptButton”和“CancelButton”属性设置为要触发对话框的接受和取消行为的按钮。

您还应该在按钮上设置“DialogResult”属性,以控制按钮导致对话框返回的特定DialogResult值。

EG,在设计器文件中用于对话的所有其他内容中,您需要最终得到如下内容:

    this.accept = new System.Windows.Forms.Button();
    this.cancel = new System.Windows.Forms.Button();
    this.other = new System.Windows.Forms.Button();

    // 
    // accept
    // 
    this.accept.DialogResult = System.Windows.Forms.DialogResult.OK;

    // 
    // cancel
    // 
    this.cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;

    // 
    // other
    // 
    this.other.DialogResult = System.Windows.Forms.DialogResult.Ignore;

    // 
    // Form2
    // 
    this.AcceptButton = this.accept;
    this.CancelButton = this.cancel;

    this.Controls.Add(this.other);
    this.Controls.Add(this.cancel);
    this.Controls.Add(this.accept);

答案 1 :(得分:1)

您需要设置frmIntegrationConfig' s DialogResult

你可以通过设置DialogResult of the Save button to DialogResult.OK 或者我更喜欢这样做,因为它很明显,btnSave_Click()方法中的DialogResult.OK发生了set the form's DialogResult

private void btnSave_Click(object sender, EventArgs e)
{ 
     // closes form and returns value to ShowDialog
     this.DialogResult = DialogResult.OK;       
}
相关问题