Search code examples
c#showdialog

Using ShowDialog() in C# to display a message


I want to use show dialog () to display a message in another form. How do I show the message? Here's what I've tried.

//return total 
return total; 

//change total to string 
total = total.ToString;

//create an instance of the MessageForm class
MessageForm myMessageForm = new MessageForm();

//Display the form
myMessageForm.ShowDialog(total);

This gives me an error message. i don't know how to go about showing the total in the other form. Any suggestions?


Solution

  • The value of total you're passing in is supposed to be the owner of this new form.

    You probably want to achieve this:

    // remove the return line
    
    total = total.ToString();
    
    //create an instance of the MessageForm class
    MessageForm myMessageForm = new MessageForm();
    
    // set the total value which is now a property on message form
    myMessageForm.Total = total;
    
    //Display the form
    myMessageForm.ShowDialog();
    

    You would also have to add this new property to MessageForm class

    // decide the visibility yourself (e.g. public vs internal)
    internal string Total { get; set; }
    

    You should also consider whether you want to pass total in the constructor as opposed to a property. If you have other existing classes calling MessageForm, this mayrequire some refactoring.