Why does ShowDialog always return DialogResult.Cancel?

徘徊边缘 提交于 2019-12-10 13:39:04

问题


I have a custom made dialog winform. On it I have a label, textbox and 2 buttons (OK and Cancel). It also declares and defines overloaded execute methods for passing different parameter list.

Dialog Winform is called as follows:

var theDialog := new InputMsgBox;

if theInputB.Execute('Awesome StackOverflow','Enter Text?',s,var s) = DialogResult.OK then
begin
  Invalidate;
  SetText(s);
end;

Dialog Winform execute is defined as follow:

method InputMsgBox.Execute(Title, theMessage, defaultanswer:string;var thevalue:string): DialogResult;
begin
    result := DialogResult.Cancel;

    Requesttext.Text:=themessage;
    Requesttext.Enabled:=true;
    Requesttext.Visible:=true;
    InputTextBox.Text:=defaultanswer;
    InputTextBox.Enabled:=true;
    InputTextBox.Visible:=true;

    CancelBtn.Enabled:=true;
    CancelBtn.Visible:=true;
    Okbtn.Enabled:=true;
    Okbtn.Visible:=true;

    self.ShowDialog;
    Result := self.DialogResult;
    thevalue:=InputTextBox.Text;
end;

When execute method returns back to the caller, it always returns DialogResult.Cancel even when you click on OKBtn.

The Buttons' dialogresult are set accordingly.

I have set the AcceptButton and CancelButton on the Dialog winform.

I can't figure out why the showdialog method is always returning DialogResult.Cancel.

UPDATE After doing some test, I found out that my other custom-made dialog window works fine when display by calling showdialog = DialogResult.Ok. So, I checked both of them to see if there are some differences in their properties setting and there is absolutely no difference. I don't understand it. Thanks in advance,


回答1:


I figured out my problem. This is why Dialog Form always returned Cancel DialogResult. For my custom-made dialog window, I also implemented Form_Closing event method. Apparently, you are not to have an event that will jump the program counter out of its steps when opening a dialog using ShowDialog method. So, it was already closed before it got a chance to read its DialogResult. Therefore, my program only saw the default DialogResult for my Dialog Window.

Once I removed the Form_Closing event method, it is working the way it is supposed to.

Instead of deleting the question, I am answering it and I feel it will help others.




回答2:


You should set a different DialogResult - for example, by setting the DialogResult property of your AcceptButton to DialogResult.OK.

Or set it programatically, often in a button event handler.

I imagine DialogResult.Cancel is the default, and you're never changing it.



来源:https://stackoverflow.com/questions/7971649/why-does-showdialog-always-return-dialogresult-cancel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!