Variable in message box c#

Asked

Viewed 1,643 times

2

How to put a variable inside the message box? The code comes below I think is self-explanatory.

 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.Windows.Forms;

 namespace A12
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        var c;
        c = 23;
    }


    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("{0}", c);
    }
}
}

4 answers

5


The code below is also self-explanatory. :)

public partial class Form1 : Form
{
    private int _c;
    public Form1()
    {
        InitializeComponent();
        _c = 23;
    }    

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("{0}", _c);
    }
}

2

Complementing a little the answer of Thiago Lunardi:

Your code does not work because the variable is being created within a scope, in this case, the public Form1(), and is being called in another scope, in this case, the button1_Click().

To do this, you would have to create the variable in a larger scope, or at least in a scope where 2 has access to variables. In your case, the class Form1 : Form:

public partial class Form1 : Form
{
    int c;

    public Form1()
    {
        InitializeComponent();
        c = 23;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show($"{c}");
    }
}

Also note that in the string of MessageBox, I printed the variable in a different way, because in this case, in which the method can receive more than 1 parameter, it can consider the variable as one. (This is only a recommendation, and in my opinion prevents errors).

  • Just to complement: "print the variable in a different way", this way is called String interpolation.

  • Interesting, I didn’t know. @Thiagolunardi

0

You can use the method Format class String.

Look at the example below:

public partial class Form1 : Form
{
    private int c;

    public Form1()
    {
        InitializeComponent();
        c = 23;
    }    

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show(String.Format("{0}", c));
    }
}

0

Creating the variable outside any method will solve the problem:

public partial class Form1 : Form
{
private int c;

public Form1()
{
    InitializeComponent();
    c = 23;
}    

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

}

You created a variable within public Form1(), and would only be able to use it inside public Form1(). If you create it within your class and outside of any method, you will be able to use it anywhere within your class.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.