Search code examples
c#overridingtostringshowdialog

C#: Why doesn't ShowDialog().ToString() return expected String?


labelTotal holds the value of class Keypad (C# WinForms). ToString has been overriden to return labelTotal.Text.

namespace Gui3
{
    public partial class Keypad : Form
    {
        public Keypad()
        {
            InitializeComponent();
        }
        public override String ToString() {return labelTotal.Text;}
        private void buttonOk_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        ...

Why doesn't keypad.ShowDialog().ToString() return labelTotal.Text?

namespace Gui3
{
    public partial class Setup : Form
    {
        public Setup()
        {
            InitializeComponent();
        }
        private void buttonStartDepth_Click(object sender, EventArgs e)
        {
            Keypad keypad = new Keypad();
            ////////// Not working as expected /////////
            String total = keypad.ShowDialog().ToString();
            ...

Solution

  • Because the ShowDialog() method returns a System.Windows.Forms.DialogResult enum value, not the instance of your form. ToString() will be called on the enum value returned by this function.

    You might try something like the following (assumes keypad will properly return DialogResult.OK):

    private void buttonStartDepth_Click(object sender, EventArgs e)
    {
        Keypad keypad = new Keypad();
    
        if (keypad.ShowDialog() == DialogResult.OK)
        {
            String total = keypad.ToString();
        }
    }