user724198
user724198

Reputation:

"Only assignment, call increment..." Error On Closing Connection

I'm a little rusty at C#, and can't figure out why I'm getting a message on AWConn.Close;:

Only assignment, call, increment, decrement and new object expressions can be used as a statement

What am I doing wrong? Here's the code.

    private void Form1_Load(object sender, EventArgs e)
    {
        SqlConnection AWConn = new SqlConnection("Driver={SQL Server Native Client 10.0};Server=MyServer/MyInstance; Database=MyDB;Integrated Security=true;");

        try
        {
            AWConn.Open();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

        // Database stuff here...

        AWConn.Close;


    }

I'm sure this looks like a dumb question, but like I said it's been awhile.

Upvotes: 1

Views: 629

Answers (1)

Soner Gönül
Soner Gönül

Reputation: 98750

SqlConnection.Close() is a method. You need to call it like;

AWConn.Close();

But instead of that, just use using statement to dispose your database connections and objects automatically.

using(SqlConnection AWConn = new SqlConnection(conString))
{
    try
    {
        AWConn.Open();
    }
    catch(SqlException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

Instead of catching an Exception, catch instead SqlException which only exception type that .Open() method can throw.

Upvotes: 2

Related Questions