Paul William Fassett
Paul William Fassett

Reputation: 17

Using Show() to display data from another class

I know how to create programs in C++, but very new to C# so be patient, but I have a question, and for the life of my couldn't find it on google, or stackoverflow search (maybe didn't know a good way to phrase it). I have two functions on my form: A NumericUpDown, and a Button. When the button is clicked, I want to grab the data from NumericUpDown, and .Show() it in a message box. Here is what I currently have.

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

    private void StatBox_ValueChanged(object sender, EventArgs e)
    {
        //decimal Stat = StatBox.Value;
        //string StatStr = Stat.ToString();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show(StatBox.Value);
    }
}

Upvotes: 1

Views: 340

Answers (2)

Cody Gray
Cody Gray

Reputation: 244812

Like C++, C# is a strongly-typed language. That means that you will get a compile-time error if you try to pass an int to a function that accepts a string, or vice versa. That's what is happening to you here.

The simplest overload of the MessageBox.Show function accepts a single string parameter, yet you've passed it a decimal (the result of StatBox.Value):

MessageBox.Show(StatBox.Value);

The fix is simple: convert the decimal to a string. All .NET objects provide a ToString member function that can be used to obtain a string representation of the object. So rewrite your code like so:

MessageBox.Show(StatBox.Value.ToString());

You can even get fancy and concatenate a number of sub-strings together when calling this function, just like you can with the C++ string type and I/O streams. For instance, you might write this code:

MessageBox.Show("The result is: " + StatBox.Value.ToString());

or use the String.Format method, which is somewhat similar to the C printf function. Then you can specify a standard or custom numeric format and avoid calling the ToString function explicitly. For example, the following code will display the number in the up-down control in fixed-point notation with exactly two decimal places:

MessageBox.Show(String.Format("The result is: {0:F2}", StatBox.Value.ToString()));

Upvotes: 2

Brian
Brian

Reputation: 5119

This should do it for you:

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

   private void StatBox_ValueChanged(object sender, EventArgs e)
   {
       //decimal Stat = StatBox.Value;
       //string StatStr = Stat.ToString();
   }

   private void button1_Click(object sender, EventArgs e)
   {
       MessageBox.Show(StatBox.Value.ToString());
   }
}

Since you are using a MessageBox to .Show() the data, you will want to call the .ToString() method on the StatBox.Value.

PS - Welcome to SO! You will love it here.

Upvotes: 1

Related Questions