Variable in message box c #

2

How to put a variable within the message box? The code comes down I think it's 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);
    }
}
}
    
asked by anonymous 24.08.2017 / 10:08

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);
    }
}
    
24.08.2017 / 10:43
1

Complementing slightly the response 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 the 2 has access to the variables. In your case, 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}");
    }
}

Note also that in the string of MessageBox , I printed the variable in a different way, because in this case, where the method can receive more than 1 parameter, it can consider the variable as one. (This is just a recommendation, and in my opinion it prevents mistakes.)

    
24.08.2017 / 12:35
0

You can use the Format method of the String class.

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));
    }
}
    
25.08.2017 / 22:29
0

Creating the variable out of 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 have created a variable within public Form1() , and you could only use it within public Form1() . If you create it within your class and out of any method, you will be able to use it anywhere within your class.

    
26.08.2017 / 01:08