Ebay Boosting
Ebay Boosting

Reputation: 27

What does error "A namespace cannot directly contain members such as fields or methods" mean?

I added following code to my C# windows form application to show a message box when i click the closing button.. But it gives me following error..

Error CS0116 A namespace cannot directly contain members such as fields or methods ebay source C:\Users\Supun\Documents\Visual Studio 2015\Projects\ebay source\ebay source\Form1.cs 107 Active

this is the code i used..

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    DialogResult dialog = dialog = MessageBox.Show(
      "Do you really want to close the program?", 
      "SomeTitle", 
       MessageBoxButtons.YesNo);

    if (dialog == DialogResult.No)
    {
        e.Cancel = true;
    }
}

What do I need to do to fix it please?

Upvotes: -1

Views: 19831

Answers (3)

Babar Khalid
Babar Khalid

Reputation: 1

Don't write dialog twice, use the following simple code and you will be fine.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{

if (MessageBox.Show("Do you really want to exit??, "Exit", MessageBoxButtons.YesNo)== DialogResult.No)
 {
    e.Cancel = true;
 }
}

Upvotes: 0

user10318605
user10318605

Reputation:

Check your function is like below. I think some variable or function are directly under the namespace. Keep them inside the class.

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

        private void button2_Click(object sender, EventArgs e)
        {
             DialogResult dialog = dialog = MessageBox.Show("Do you really want to close the program?", "SomeTitle", MessageBoxButtons.YesNo);
             if (dialog == DialogResult.No)
             {
                 e.Cancel = true;
             }
        }
    }
}

Upvotes: 2

cgt_mky
cgt_mky

Reputation: 196

I would imagine you've declared that function outside of a class?

Like

namespace Something
{
    private void Method()
    {
    }
}

Instead of

namespace Something
{
    class MyClass
    {
        private void Method()
        {
        }
    }
}

Upvotes: 12

Related Questions