Is it possible to overload the ShowDialog method for forms and return a different result?

只愿长相守 提交于 2019-12-04 01:51:29

Edit: It's proberly not a good idea to change the functionality of ShowDialog(), people expect it to return a DialogResult and show the form, I suggest something like my suggestion below. Thus, still allowing ShowDialog() to be used the normal manner.

You could create a static method on your MyForm, something like DoShowGetResult()

which would look something like this

public static MyResultsForm DoShowGetResult()
{
   var f = new MyForm();
   if(f.ShowDialog() == DialogResult.OK)
   {
      return f.Result;   // public property on your form of the result selected
   }
   return null;
}

then you can use this

MyFormsResult result = MyForm.DoShowGetResult();
Snowpaque

Try this, it seems to work for me:

 public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        public DialogResult ShowDialog(string mes)
        {
            this.textBox1.Text = mes;
            return base.ShowDialog();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }

No, it's not possible. The usual workaround is to expose your real result as a property on the Form:

public MyFormResults MyResult
{
    get;
}

and you would then set this:

private void btn1_click(object sender, EventArgs e)
{
    MyResult = MyFormsResults.Result1;
    this.DialogResult = DialogResult.OK; //Do I need this for the original ShowDialog() call?
    this.Close(); //Should I close the dialog here or in my new ShowDialog() function?
}

and the calling code usually looks like this:

if (form.ShowDialog == DialogResult.OK)
{
    //do something with form.MyResult
}

The ShowDialog method cannot be overriden. What you could do intead though is create a new method which returns both the ShowDialog result and another value.

public ShowDialogResult ShowDialogWrappe(out MyFormResults result) { 
  var dialogRet = ShowDialog();
  result = MyFormResults.Result1;
  return dialogRet;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!