简体   繁体   中英

What does “A new expression requires (), [], or {} after type” mean?

This is my code:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Data;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = "Data Source=OCS-MXL930055N\\;Initial           Catalog=sample;Integrated Security=True";
        SqlCommand cmd = new SqlCommand

        con.Open("Select * from ShoppingList", con);

        con.Close("Select * from ShoppingList", con);
    }
}

And these are the lines I am having problems with:

con.Open("Select * from ShoppingList", con)();

con.Close("Select * from ShoppingList", con)();

Any help with what they mean? I'm not too sure what I'm doing wrong.

Your statement:

SqlCommand cmd = new SqlCommand

should be :

SqlCommand cmd = new SqlCommand("Select * from ShoppingList");

Later when you are opening and closing the connection, just remove the parameters, these parameters are required for SqlCommand constructor.

You may have your code like:

using(SqlConnection con = new SqlConnection("Data Source=OCS-MXL930055N\\;Initial Catalog=sample;Integrated Security=True"))
using(SqlCommand cmd = new SqlCommand("Select * from ShoppingList", con))
{
    //.. code to execute command
}

Read about basic C#, constructors and ADO.Net Examples on MSDN

C# isn't ruby you need to make your intent known. There are 3 ways to instantiate an object, all using the new operator:: eg

var myObj = new MyObj(); // call a constructor (parameterless)
var myObjArray = new MyObj[10]; // create an array of 10 MyObjs
var myObj = new MyObj{someProperty="someValue"}; // initializer notation.

Note you can mix the array and initializer so you can do this and its legals::

var myInts = new int[]{1,2,3,4,5,6}; //create an int array with 6 values.

To fix your snippet you need to add parens like so::

   SqlCommand cmd = new SqlCommand();

If you are sending strings of sql I strongly recommend using the library Dapper-Dot-Net found on nuget.

You haven't correctly created your SqlCommand instance:

SqlCommand cmd = new SqlCommand

turns into:

SqlCommand cmd = new SqlCommand("Select * from ShoppingList");

which in turn means:

con.Open("Select * from ShoppingList", con)();

becomes simply:

con.Open();

and similarly with con.Close(); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM