2

I have the following C# code:

public string TargetDate()
{
    SqlConnection con = 
        new SqlConnection("Server=localhost;Database=Timer;Trusted_Connectopn=True");
    SqlCommand cmd = new SqlCommand("select * from Timer");
    con.Open(); 

    DataSet ds = new DataSet(cmd,con); 
    SqlDataAdapter da = new SqlDataAdapter(); 
    da.Fill(ds); 
    con.Close(); 
}

but I get error at the: new DataSet(cmd,con); ...

the error: CS1502: The best overloaded method match for

'System.Data.DataSet.DataSet(System.Runtime.Serialization.SerializationInfo,

System.Runtime.Serialization.StreamingContext)' has some invalid arguments

What is could be the problem?

2
  • Hi, the connection string should be "Server=localhost;Database=Timer;Trusted_Connection=True". Thanks. Commented May 17, 2011 at 7:10
  • You can also try the documentation on MSDN, Populating a DataSet from a DataAdapter Commented May 17, 2011 at 7:12

3 Answers 3

5

Try this:

SqlConnection con = new SqlConnection
    ("Server=localhost;Database=Timer;Trusted_Connection=True");

SqlCommand cmd = new SqlCommand("select * from Timer", con);

con.Open();

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);

con.Close(); 

This is even better:

DataTable dataTable = new DataTable();
using(SqlConnection connection = new SqlConnection("Server=localhost;Database=Timer;Trusted_Connection=True"))
using(SqlCommand command = connection.CreateCommand())
{
    command.CommandText = "select * from Timer";
    connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    dataTable.Load(reader);
}
Sign up to request clarification or add additional context in comments.

3 Comments

does using CommandBehavior.CloseConnection in ExecuteReader make a difference ?
Plus: fix the typo Trusted_Connection=True instead of Trusted_Connectopn=True
+1 for the using....... blocks! And even better yet: don't use SELECT * but explicitly specify the columns that you really need...
4

You've got the wrong constructor for the DataSet. Try this

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(con);

3 Comments

Is there a SqlDataAdapter constructor that takes SqlCommand and SqlConnection?
@Alex: Ah I see, I confused the string "selectCommandText" with the SqlCommand object. You are right.
Wow 3 upvotes for something inconsistent ! i believe you should clarify that cmd is a string and not a command object
0

It seems you have mixed up the constructors:

Try the following:

DataSet ds = new DataSet(); 

SqlDataAdapter da = new SqlDataAdapter(con); 

Hope that helps

1 Comment

Is there a SqlDataAdapter constructor that takes SqlCommand and SqlConnection?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.